按分区或级别SQL的行之间的日期差异

时间:2017-05-16 02:41:38

标签: sql sql-server datediff partition-by

我正在使用Microsoft SQL Server。我有一个表用户ID和登录日期。我的日期最初存储为Datetime,但我将它们转换为日期。我需要显示按用户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

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

;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结婚。

1 个答案:

答案 0 :(得分:3)

使用lag()

select cte.*,
       datediff(day,
                lag(login_date) over (partition by user_id order by login_date),
                login_date
               ) as diff
from cte;