两行之间的差异,日期按升序排列

时间:2016-03-31 04:17:14

标签: sql sql-server tsql

我正在尝试编写一个查询,当datetime字段按升序排列时,它会计算值行之间的差异,作为名为差异的新列。

例如,2016-03-02应为102340624 - 102269208

select datetime, tagname, value
from runtime.dbo.AnalogHistory
where datetime between '20160301 00:00' and '20160401 00:00'
and TagName = 'EWS_A3_PQM.3P_REAL_U'
and wwResolution = (1440 * 60000)
order by DateTime asc

DATETIME                    TAGNAME                 VALUE       DIFFERENCE
2016-03-01 00:00:00.0000000 EWS_A3_PQM.3P_REAL_U    102269208
2016-03-02 00:00:00.0000000 EWS_A3_PQM.3P_REAL_U    102340624
2016-03-03 00:00:00.0000000 EWS_A3_PQM.3P_REAL_U    102411568
2016-03-04 00:00:00.0000000 EWS_A3_PQM.3P_REAL_U    102478104
2016-03-05 00:00:00.0000000 EWS_A3_PQM.3P_REAL_U    102549088
2016-03-06 00:00:00.0000000 EWS_A3_PQM.3P_REAL_U    102612592
2016-03-07 00:00:00.0000000 EWS_A3_PQM.3P_REAL_U    102682984
2016-03-08 00:00:00.0000000 EWS_A3_PQM.3P_REAL_U    102747000
2016-03-09 00:00:00.0000000 EWS_A3_PQM.3P_REAL_U    102817176
2016-03-10 00:00:00.0000000 EWS_A3_PQM.3P_REAL_U    102887896

非常感谢您提前

3 个答案:

答案 0 :(得分:2)

您可以使用滞后函数来获取先前的行值。

Select datetime, tagname, value, value- coalesce(lag(value) over(partition by tagname order by datetime),0) [difference]
from runtime.dbo.AnalogHistory
where datetime between '20160301 00:00' and '20160401 00:00'
and TagName = 'EWS_A3_PQM.3P_REAL_U'
and wwResolution = (1440 * 60000)
order by DateTime asc

答案 1 :(得分:0)

对于sql server版本2005或更高版本但在2012之前(你没有滞后和主导功能)

;with cte as 
(
    select datetime, tagname, value
    from runtime.dbo.AnalogHistory
    where datetime between '20160301 00:00' and '20160401 00:00'
    and TagName = 'EWS_A3_PQM.3P_REAL_U'
    and wwResolution = (1440 * 60000)
)

select datetime, tagname, value, value - isnull((select top 1 value from cte t2 where t2.datetime < t1.datetime order by t2.datetime desc), 0) as difference
from cte t1 
order by DateTime

对于sql server 2012或更高版本:

select datetime, tagname, value, value - isnull(lag(value) over (order by datetime), 0)
from runtime.dbo.AnalogHistory
where datetime between '20160301 00:00' and '20160401 00:00'
and TagName = 'EWS_A3_PQM.3P_REAL_U'
and wwResolution = (1440 * 60000)
order by DateTime

答案 2 :(得分:0)

这适用于任何版本..您需要做的是为您的日期添加+1以获取下一列,对于最后一列,您显然不会有下一个值,您可以使用null函数来自定义..

select 
 t1.*,isnull(b.difference ,t1.value) as difference  from yourtable t1
outer apply
(
select (t2.value-t1.value) as difference from yourtable t2 
where dateadd(day,1,t1.date)=t2.date
) b