How to get previous and current row value using recursive CTE?

前端 未结 1 846
日久生厌
日久生厌 2021-01-06 07:37

Consider the below

Id  Nums
1   10
2   20
3   30
4   40
5   50

The expected output

Id  CurrentValue    PreviousValue
1   10         


        
相关标签:
1条回答
  • 2021-01-06 08:37

    This assumes increasing ID values and will deal with gaps in ID

    SELECT
       ID, 
       This.Number AS CurrentValue, 
       Prev2.Number AS PreviousValue
    FROM
       myTable This
       OUTER APPLY
       (
        SELECT TOP 1
           Number
        FROM
           myTable Prev
        WHERE
           Prev.ID < This.ID  -- change to number if you want
        ORDER BY
           Prev.ID DESC
       ) Prev2;
    

    OR

    WITH CTE
         AS (SELECT ID,
                    Number,
                    ROW_NUMBER() OVER (ORDER BY ID) AS rn
             FROM   Mytable)
    SELECT ID,
           This.Number AS CurrentValue,
           Prev.Number AS PreviousValue
    FROM   CTE This
           LEFT JOIN CTE Prev
             ON Prev.rn + 1 = This.rn; 
    

    And for SQL Server 2012

    SELECT
       ID,
       Number AS CurrentValue,
       LAG(Number) OVER (ORDER BY ID) AS PreviousValue
    FROM
       MyTable
    
    0 讨论(0)
提交回复
热议问题