Reputation: 17617
(Please note that I have seen a similar question on StackOverflow recently, however I can not find it anywhere - if anyone can find it please post the link)
I have a table that has a datetime field in it. For example:
Table data
DateTime date;
int number;
I need to find the difference between date in a row and date in the next row. I have tried with a query:
select date as current_date, date - (select top 1 date where date > current_date from data) as time_difference from date
however this won't work, because of "current_date". Is there a way I can do this with one query?
Upvotes: 1
Views: 1864
Reputation: 425261
SELECT date AS current_date, next_date - date AS difference
FROM mytable mo
CROSS APPLY
(
SELECT TOP 1 date AS next_date
FROM mytable mi
WHERE mi.date > mo.date
ORDER BY
date
) q
Upvotes: 3