Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
HI,I have a table with a Date-Time column with the below values10:3010:3511:0011:10I need to calculate the sum of difference of consecutive rows , for example10:35 - 10:30 = 511:00 - 10:35 = 2511:10 - 11:00 = 10And then total the sum = 5+25+10 = 40I am trying out the best way to get the sum, help needed.Thanks in advance
khtan
In (Som, Ni, Yak)
17689 Posts
Posted - 2007-09-12 : 01:35:51
[code]DECLARE @TABLE TABLE( [time] datetime)INSERT INTO @TABLESELECT '10:30' UNION ALLSELECT '10:35' UNION ALLSELECT '11:00' UNION ALLSELECT '11:10'SELECT [the SUM] = SUM(DATEDIFF(minute, t1.[time], t2.[time]))FROM ( SELECT [time], row = row_number() OVER (ORDER BY [time]) FROM @TABLE) t1INNER JOIN( SELECT [time], row = row_number() OVER (ORDER BY [time]) FROM @TABLE) t2ON t1.row = t2.row - 1[/code]KH[spoiler]Time is always against us[/spoiler]
Babli
Yak Posting Veteran
53 Posts
Posted - 2007-09-12 : 01:41:23
Thanks a lot,I was trying with cursors but this is a easy and quick solution.
SwePeso
Patron Saint of Lost Yaks
30421 Posts
Posted - 2007-09-12 : 01:45:10
And if you don't want to calculate the row_number() twice
;WITH Yak (Time, Row)AS ( SELECT [time], row_number() OVER (ORDER BY [time]) FROM @TABLE)SELECT [the SUM] = SUM(DATEDIFF(minute, t1.[time], t2.[time]))FROM Yak AS t1 INNER JOIN Yak AS t2 ON t2.row - 1 = t1.row