DATEDIFF(按用户ID)

时间:2018-06-29 14:21:19

标签: sql sql-server

我想知道是否有一种方法可以通过用户ID计算datediff()。例如,我有:

SELECT USER_ID, DATE, ?*
FROM TABLE_1
WHERE DATE BETWEEN 2018-01-01 AND 2018-01-31

会拉:

USER_ID     DATE          DATEDIFF
001         2018-01-01    -
001         2018-01-05    5
002         2018-01-02    -
003         2018-01-03
003         2018-01-05    2

*有问题的查询是,如果存在两个或多个相同的User_ID,是否有一种方法可以仅计算按user_id分组的两个日期之间的差异。

3 个答案:

答案 0 :(得分:1)

使用LAG()或更可扩展的方式:

DECLARE @user TABLE
(
    UserId INT,
    DateColumn DATE
)

INSERT @user VALUES (1, '2018/06/30');
INSERT @user VALUES (1, '2018/06/30'); 
INSERT @user VALUES (2, '2018/06/30');
INSERT @user VALUES (3, '2018/06/30');
INSERT @user VALUES (3, '2018/07/01'); 
INSERT @user VALUES (3, '2018/07/02');


SELECT UserId, DateColumn, DATEDIFF(DAY, MinDate, MaxDate) AS Diff
FROM (
    SELECT UserId, DateColumn, MIN(DateColumn) OVER(PARTITION BY UserId) AS MinDate, MAX(DateColumn) OVER(PARTITION BY UserId) AS MaxDate
    FROM @user
) AS sub

答案 1 :(得分:1)

您似乎想要lag()

select *, datediff(dd, prev, dt) as dtdiff
from (select *, lag(dt) over (partition by id order by dt) prevdt
      from table
     ) t;

答案 2 :(得分:1)

我看不到5的来源。我认为应该是4。

您可以这样做:

select user_id, date,
       datediff(day, lag(date) over (partition by user_id order by date), date) as diff
from t;