简体   繁体   English

来自同一列的减值

[英]Minus values from the same column

I have a table with 2 columns.我有一个有 2 列的表。 one contains the user's ID and the other contains the datetime whenever that user logged into the application.一个包含用户的 ID,另一个包含该用户登录应用程序时的日期时间。

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).我在 AdventureWorks 数据库中摆弄,可能已经找到了一种方法来获得你正在寻找的东西(虽然我是新手,所以有更多经验和知识的人可能会有更好的主意)。 But hopefully this provides some starting point.但希望这提供了一些起点。 I created 2 CTEs with Row_Number, second CTE had Row_Number-1 as it's count.我用 Row_Number 创建了 2 个 CTE,第二个 CTE 有 Row_Number-1 作为计数。 Then joined those two CTEs and did a datediff on the event_datetimes.然后加入这两个 CTE 并在 event_datetimes 上做了一个 datediff。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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