日期:2014-05-18  浏览次数:20435 次

查询一年中每个月的差值
有如下表:
ID datetime value
1 2011-1-2 50
2 2011-1-3 30
3 2011-1-3 20
1 2011-2-1 56
2 2011-2-4 35
1 2011-2-4 63
3 2011-2-4 34





1 2012-1-1 1000
3 2012-1-2 1200
2 2012-1-4 1100


就是说有三个设备,然后每个设备每月都会收到1次以上数据,需要做的是,客户给出需要查的设备ID和时间段,然后查询显示出每月差值,每月的值以最早收到的为准,如果本月一次都没收到,那么按上月的值计算。

例如:
用户查询,id号为1和2的表,数据要看2011年的
那么查询后的表如下

id 1月 2月 3月 4月 5月 6月 7月 8月 9月 10月 11月 12月
1 5 4 5 6 6 7 7 8 9 9 0 5
2 4 5 6 7 6 5 8 4 3 2 4 4

请问如何实现,谢谢

------解决方案--------------------
id 1月 2月 3月 4月 5月 6月 7月 8月 9月 10月 11月 12月
1 5 4 5 6 6 7 7 8 9 9 0 5
2 4 5 6 7 6 5 8 4 3 2 4 4

没看出来你这些数据是怎么得来的,麻烦你解释一下
------解决方案--------------------
select B.id,case datepart(mm,YF) when 1 then value else null end [1月],
case datepart(mm,getdate()) when 2 then value else null end [2月],
case datepart(mm,getdate()) when 3 then value else null end [3月],
case datepart(mm,getdate()) when 4 then value else null end [4月],
case datepart(mm,getdate()) when 5 then value else null end [5月],
case datepart(mm,getdate()) when 6 then value else null end [6月],
case datepart(mm,getdate()) when 7 then value else null end [7月],
case datepart(mm,getdate()) when 8 then value else null end [8月],
case datepart(mm,getdate()) when 9 then value else null end [9月],
case datepart(mm,getdate()) when 10 then value else null end [10月],
case datepart(mm,getdate()) when 11 then value else null end [11月],
case datepart(mm,getdate()) when 12 then value else null end [12月] 
from tb B
inner join
(
select ID,YF,MIN(datetime) datetime
from
(
select ID,datepart(mm,datetime)) as YF,datetime from tb
) A 
group by ID,YF
) C on C.ID = B.ID and B.datetime = C.datetime

这个SQL语句中没有处理“如果本月一次都没收到,那么按上月的值计算”,现在显示为NULL值,你可以把这个结果插入临时表后,再处理一下就OK了