I am trying to do something I don't know if it's doable. I have this query:
SELECT [CreatedOn]
FROM [MyTable]
As you can see in the image, there are different dates. Now what I want to achieve is to get the time difference between each date/time in each row. For example, diference between date in row1 and row2, then row2 and row3, etc... Is that possible? Thanks, Laziale
You can create a cte with row number then outer join on the next row to get the datediff
;with t as (
SELECT
[CreatedOn],
rn = row_number() over(order by [CreatedOn])
FROM
[MyTable]
)
select
t.[CreatedOn],
secondsTilNext = datediff(s, t.[CreatedOn], tnext.[CreatedOn])
from
t
left outer join t tnext on tnext.rn = t.rn + 1
;WITH q AS (
SELECT
CreatedOn,
ROW_NUMBER() OVER (ORDER BY CreatedOn) AS rn
FROM
MyTable
)
SELECT
q1.CreatedOn AS Date,
q2.CreatedOn AS NextDate,
DATEDIFF(SECOND, q1.CreatedOn, q2.CreatedOn) AS SecondDiff
FROM
q q1 JOIN
q q2 ON q1.rn + 1 = q2.rn
Assuming you are using C# to access your data, there is a good reference here: http://msdn.microsoft.com/en-us/library/aa287590(v=vs.71).aspx
Basically, the code is
DateTime oldDate = new DateTime(2002,7,15);
DateTime newDate = DateTime.Now;
// Difference in days, hours, and minutes.
TimeSpan ts = newDate - oldDate;
// Difference in days.
int differenceInDays = ts.Days;
Any .NET language you use should support something similar to this. I've done the same thing in Python many times.
Try datediff MSDN Datediff
Or perhaps
cast((date1-date2) as varchar(255))
Syntax might be wrong, I can't check it at the moment.
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.