简体   繁体   中英

sql query for difference between current row and previous row based on datetime

i have a small issue in sql query. I am using SQL Server 2008 Database, i want to calculate the difference between current row and previous row of column cumulativeValue based on datetime in where condition i need to pass siteid , from date and todate in between days i need to get the data. the table is below:

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

Output should be:

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

Please help me in this query thank you :-)

In SQL Server 2012+, you can use lag() . In SQL Server 2008, use 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;

You van use common table expression and ROW_Number() and join the rows on A.row = B.row - 1. Like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM