1

我正在使用 Microsoft SQL Server。我有一个表用户 ID 和登录日期。我将日期最初存储为日期时间,但我将它们转换为日期。我需要显示按用户 ID 分组的每个登录之间的日期差异(以天为单位);如果用户 ID 更改,我希望该功能不计算登录之间的差异。我的表的一个例子是:

user_id, login_date
356,2012-03-22
356,2012-03-22
356,2012-03-22
356,2012-03-23
356,2012-07-17
356,2012-07-19
356,2012-07-20
381,2011-11-28
473,2011-12-29
473,2011-12-29
473,2011-12-29
473,2011-12-29
473,2012-01-13
473,2012-01-26
473,2012-01-29

有许多类似的帖子,我试图建立我的查询。但是,我输出的 datediff 似乎并不总是与日期匹配。这是我最近的尝试:

;with cte AS (SELECT *,ROW_NUMBER() OVER(PARTITION BY login.user_id 
ORDER BY login.user_id, login.login_date) AS RN 
          FROM login)
SELECT a.user_id, a.login_date ,datediff(day, a.login_date, b.login_date)
FROM cte a
LEFT JOIN cte b
ON a.user_id = b.user_id
and a.rn = b.rn -1

输出样本为:

user_id, login_date
356,2012-03-22,0
356,2012-03-22,0
356,2012-03-22,0
356,2012-03-23,0
356,2012-07-17,1
356,2012-07-19,0
356,2012-07-20,0
381,2011-11-28,0
473,2011-12-29,0
473,2011-12-29,0
473,2011-12-29,0
473,2011-12-29,0
473,2012-01-13,11
473,2012-01-26,3
473,2012-01-29,0

我没有结婚使用cte。

4

1 回答 1

9

使用lag()

select cte.*,
       datediff(day,
                lag(login_date) over (partition by user_id order by login_date),
                login_date
               ) as diff
from cte;
于 2017-05-16T02:44:07.860 回答