sql 求差值

有一组数据,这组数据是不断增加的,想求每小时的差值,规则是:本小时差值=后一小时第一个数据减去本小时第一个数据,中间数据可以忽略不管
如下表
DT            Value
2008-1-1 1:01 23
2008-1-1 1:32 25
2008-1-1 1:59 27
2008-1-1 2:06 28
2008-1-1 2:46 29
2008-1-1 3:06 37
2008-1-1 3:26 41
2008-1-1 3:56 42
2008-1-1 4:00 42

结果为
DT          Value
2008-1-1 1时 5      (28-23)
2008-1-1 2时 9      (37- 28)
2008-1-1 3时 5      (42- 37)
这个问题第1个回答:

DT            Value
这个问题第2个回答:
SQL code


select convert(char(10),c.dt,120),a.value - b.value as value

from (

select * from ta a where not exists(select 1 from ta where convert(char(13),a.dt,120) = convert(char(13),dt,120) and dt > a.dt)

) c

left join (

select * from ta a where not exists(select 1 from ta where convert(char(13),a.dt,120) = convert(char(13),dt,120) and dt < a.dt) b

on convert(char(13),c.dt,120)= convert(char(13),b.dt,120)

作者:水木    
 
原文地址:https://www.cnblogs.com/hsapphire/p/1626301.html