查询一年中每个月的差值

aaa6263 2012-02-13 05:37:05
有如下表:
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

请问如何实现,谢谢
...全文
67 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
aaa6263 2012-02-15
  • 打赏
  • 举报
回复
谢谢楼上
好像还不行
求助
老猫五号 2012-02-14
  • 打赏
  • 举报
回复
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了
  • 打赏
  • 举报
回复
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

没看出来你这些数据是怎么得来的,麻烦你解释一下

22,206

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧