按分区或级别划分的行之间的日期差异 SQL
Date difference between rows by partition or level SQL
我正在使用 Microsoft SQL 服务器。我有一个 table 用户 ID 和登录日期。我将日期最初存储为日期时间,但我将它们转换为日期。我需要显示按用户 ID 分组的每次登录之间的日期差异(以天为单位);如果用户 ID 更改,我希望该函数不计算登录之间的差异。我的 table 的一个例子是:
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。
使用lag()
:
select cte.*,
datediff(day,
lag(login_date) over (partition by user_id order by login_date),
login_date
) as diff
from cte;
我正在使用 Microsoft SQL 服务器。我有一个 table 用户 ID 和登录日期。我将日期最初存储为日期时间,但我将它们转换为日期。我需要显示按用户 ID 分组的每次登录之间的日期差异(以天为单位);如果用户 ID 更改,我希望该函数不计算登录之间的差异。我的 table 的一个例子是:
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。
使用lag()
:
select cte.*,
datediff(day,
lag(login_date) over (partition by user_id order by login_date),
login_date
) as diff
from cte;