在线等请教高手一个SQL问题!看能否实现?
我的一个表里面有这样两个栏位Qty 为数量 Sdate 为时间.
现在是想查某个月时分别会出现两个栏位,比如说产生Qty1为要查的某个月的数量,qty2为某个月的前一个月的数量!
Qty Sdate
100 2007-05
200 2007-06
500 2007-04
30 2007-07
查2007-06时产生如下:
Qty1 Qty2
200 100
谢谢!
------解决方案-------------------- select distinct (case right(Sdate,2)=month(getdate()) then Qty end ) as Qty1,
(case right(Sdate,2)=month(getdate())-1 then Qty end ) as Qty2
from table
------解决方案--------------------declare @date varchar(20)
set @date= '2007-06 ' --条件
select
max(case when sdate=convert(varchar(7),dateadd(month,-1,@date+ '-01 '),120) then qty end) as qty1,
max(case when sdate=@date then qty end) as qty2
from tablename
------解决方案--------------------select a.Qty Qty1,b.Qty Qty2 from 表 a left join 表 b
on datediff(a.Sdate+ '-1 ',b.Sdate+ '-1 ')=1 where a.Sdate= '2007-06 '
------解决方案--------------------declare @t table(Qty int, Sdate char(7))
insert @t select 100, '2007-05 ' union
select 200, '2007-06 ' union
select 500, '2007-04 ' union
select 30, '2007-07 '
declare @d char(7)
set @d = '2007-06 '
select sum(case when sdate = @d then Qty end) as quy1,
sum(case when sdate = convert(char(7),dateadd(mm,1,@d+ '-01 ' ),120) then qty end) as qty2
from @t
/*
quy1 qty2
----------- -----------
200 30
*/