简体   繁体   中英

Minus values from the same column

I have a table with 2 columns. one contains the user's ID and the other contains the datetime whenever that user logged into the application.

I want to create a custom computation where the datetime value from the same column subtracts each other , as the latest datetime will minus the previous datetime of that latest datetime, and keeps going like that til the first-time login datetime of that user.

Right now I have no clue on how to code this computation so I really need your help and would very appreciate it.

Sample date:

样本数据

I fiddled around in the AdventureWorks db and might have found a way to get what you are looking for(although I am new to this, so someone with more experience and knowledge might have a better idea). But hopefully this provides some starting point. I created 2 CTEs with Row_Number, second CTE had Row_Number-1 as it's count. Then joined those two CTEs and did a datediff on the event_datetimes.

WITH Example_CTE (Row, UserID, Event_datetime)
AS
(
SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS Row
,UserID
,Event_datetime
FROM table
ORDER BY UserID,Event_datetime DESC
)
,
Example_CTE2 (Row, UserID, Event_datetime)
AS
(
SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL))-1 AS Row
,UserID
,Event_datetime
FROM table
ORDER BY UserID, Event_datetime DESC
)

SELECT Example_CTE.UserID
,DATEDIFF(day, Example_CTE.Event_datetime, Example_CTE2.Event_datetime) as TimeDiff
FROM Example_CTE 
left outer join Example_CTE2 on Example_CTE.row = Example_CTE2.Row

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