代码之家  ›  专栏  ›  技术社区  ›  JonWay

基于用户的上一行减去下一行

  •  1
  • JonWay  · 技术社区  · 6 年前

    我有以下数据,我想根据UserID从上一行减去当前行。我试过下面的代码没有给我想要的

    DECLARE @DATETBLE TABLE (UserID INT, Dates DATE)
    INSERT INTO @DATETBLE VALUES
    (1,'2018-01-01'), (1,'2018-01-02'), (1,'2018-01-03'),(1,'2018-01-13'),
    (2,'2018-01-15'),(2,'2018-01-16'),(2,'2018-01-17'), (5,'2018-02-04'),
    (5,'2018-02-05'),(5,'2018-02-06'),(5,'2018-02-11'), (5,'2018-02-17')
    
    
    ;with cte as (
          select UserID,Dates, row_number() over (order by UserID) as seqnum
          from @DATETBLE t
         )
    select t.UserID,t.Dates, datediff(day,tprev.Dates,t.Dates)as diff
    from cte t left outer join
         cte tprev
         on t.seqnum = tprev.seqnum + 1;
    

    电流输出

    UserID  Dates   diff
    1   2018-01-01  NULL
    1   2018-01-02  1
    1   2018-01-03  1
    1   2018-01-13  10
    2   2018-01-15  2
    2   2018-01-16  1
    2   2018-01-17  1
    5   2018-02-04  18
    5   2018-02-05  1
    5   2018-02-06  1
    5   2018-02-11  5
    5   2018-02-17  6
    

    我的预期产出

      UserID    Dates   diff
        1   2018-01-01  NULL
        1   2018-01-02  1
        1   2018-01-03  1
        1   2018-01-13  10
        2   2018-01-15  NULL
        2   2018-01-16  1
        2   2018-01-17  1
        5   2018-02-04  NULL
        5   2018-02-05  1
        5   2018-02-06  1
        5   2018-02-11  5
        5   2018-02-17  6
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   Yogesh Sharma    6 年前

    你的标签( sql-server-2008 )建议我使用 APPLY

    select t.userid, t.dates, datediff(day, t1.dates, t.dates) as diff
    from @DATETBLE t outer apply
         ( select top (1) t1.*
           from @DATETBLE t1
           where t1.userid = t.userid and
                 t1.dates < t.dates
           order by t1.dates desc
         ) t1;
    
        2
  •  2
  •   Yogesh Sharma    6 年前

    如果您有SQL Server 2012或更高版本,则可以使用 LAG() 使用按用户ID划分的分区:

    SELECT UserID
         , DATEDIFF(dd,COALESCE(LAG_DATES, Dates), Dates) as diff
    
    FROM
    
    (
    SELECT UserID
         , Dates
         , LAG(Dates) OVER (PARTITION BY UserID ORDER BY Dates) as LAG_DATES
    
    FROM @DATETBLE
    ) exp
    

    不过,这将为序列中的第一个日期提供0值,而不是空值。