日期:2014-05-17  浏览次数:20575 次

SQL 如何查询上一个月的数据
我写了个SQL语句是查询出来
Select t_PANewData .FPA1109 AS 起点系数,t_PANewData .FPA1021 AS 工资系数,t_PANewData .FEmpID AS 职员内码,
t_PA_Item.FName AS 职员姓名
from t_PANewData inner join t_PA_Item on t_PANewData.FEmpID=t_PA_Item.FItemID

现在我想查询上个月的这些数据 该表无时间字段 有2012年这样的字段 有 1,2,3,4 这样的月份字段

我想查询出来 3月的同时也显示出来2月的数据

求写法。

------解决方案--------------------
拼接起来了再用DATEADD函数和UNION ALL
------解决方案--------------------
你这两个表的结构是怎样的?两个表之间的关系又是怎样的?
------解决方案--------------------
SQL code

if OBJECT_ID('test')is not null
drop table test
go
create table test(
[year] int,
[month] int
)
go
insert test
select 2011,8 union all
select 2011,9 union all
select 2011,10 union all
select 2011,11 union all
select 2011,12 union all
select 2012,1 union all
select 2012,2 union all
select 2012,3 union all
select 2012,4 union all
select 2012,5 union all
select 2012,6 union all
select 2012,7 union all
select 2012,8 union all
select 2012,9
go


select * from test 
where [year]=case when month(GETDATE())<>1 
then year(getdate()) else year(getdate())-1 end
and [month]=(case when month(GETDATE())=1 then 12 else month(GETDATE())-1 end)
/*
year    month
-----------------
2012    5
*/