我在sql查询中有一个小问题。我正在使用SQL Server 2008数据库,我想基于 datetime 计算当前行和上一行列的累积值之间的差异,其中条件我需要通过 siteid ,<强烈的>从日期和 todate 在我需要获取数据的几天之内。表格如下:
ID siteId readtime cumulativeValue
1 GAF1608187 2017-10-18 12:59:03.000 20
2 GAF1604620 2017-10-18 11:38:33.000 10
3 GAF1608187 2017-10-19 14:59:00.000 40
4 GAF1608187 2017-10-19 16:07:46.000 65
5 GAF1604620 2017-10-19 11:41:49.000 55
6 GAF1604620 2017-10-20 10:52:35.000 120
7 GAF1608187 2017-10-20 16:10:15.000 90
8 GAF1608187 2017-10-21 16:13:19.000 120
9 GAF1604620 2017-10-21 11:44:42.000 180
10 GAF1604620 2017-10-22 11:05:50.000 230
输出应为:
ID siteId readtime cumulativeValue difference
2 GAF1604620 2017-10-18 11:38:33.000 10 10
5 GAF1604620 2017-10-19 11:41:49.000 55 45
6 GAF1604620 2017-10-20 10:52:35.000 120 75
9 GAF1604620 2017-10-21 11:44:42.000 180 60
10 GAF1604620 2017-10-22 11:05:50.000 230 50
请帮我解决这个问题谢谢: - )
答案 0 :(得分:2)
在SQL Server 2012+中,您可以使用lag()
。在SQL Server 2008中,使用apply
:
select t.*,
coalesce(t.cumulativeValue - tprev.cumulativeValue, t.cumulativeValue) as diff
from t outer apply
(select top 1 tprev.*
from t tprev
where tprev.siteId = t.siteId and tprev.readtime < t.readtime
order by tprev.readtime desc
) tprev;
答案 1 :(得分:0)
你使用公共表表达式和ROW_Number()并加入A.row = B.row上的行 - 1.像这样:
WITH CTE AS
(
SELECT TOP 10 DATECOLUMN, ROW_NUMBER() OVER (ORDER BY DATECOLUMN) AS ROW_Num
FROM Table_A
)
SELECT * FROM CTE AS A
INNER JOIN CTE AS B ON A.ROW_Num = B.ROW_Num - 1
ORDER BY A.ROW_Num