SQL Creating a new column with previous dates in new column

帅比萌擦擦* 提交于 2019-12-08 03:34:37

问题


I would Like get below result in SQL Server (Color Coded)

The Column Required is How I would like my Dates to be:

Or this link http://imgur.com/easxkMH

The new dates have to be specific to that ID

I was thinking of creating a new column of sequence(1, 2, 3,...) number per ID and another column where it is incremented by 1 (NULL, 1, 2, 3) and then doing a self left join.

Please advice on any other procedure and help with the code

Thanks


回答1:


You can use LEAD and LAG

Syntax

LEAD (scalar_expression [,offset] [,default])
    OVER ( [ partition_by_clause ] order_by_clause )

LAG (scalar_expression [,offset] [,default])
    OVER ( [ partition_by_clause ] order_by_clause )

SELECT    Id, Date
        , LEAD(Date) OVER (ORDER BY Id) AS [Next Date]
        , LAG(Date) OVER (ORDER BY Id) AS [Prev Date]
        , LEAD(Date, 2) OVER (ORDER BY Id) AS [2nd Next Date]
        , LAG(Date, 2) OVER (ORDER BY Id) AS [2nd Prev Date]
        , LEAD(Date, 2, 0) OVER (ORDER BY Id) AS [2nd Next Date]
        , LAG(Date, 2, 0) OVER (ORDER BY Id) AS [2nd Prev Date]
FROM    @Test_table



回答2:


You can put your table in CTE with ROW_NUMBERs and then join this CTE with itself:

;WITH cte AS (
SELECT  y.ID,
        y.[DATE],
        ROW_NUMBER() OVER (PARTITION BY y.ID ORDER BY (SELECT NULL)) RN
FROM YourTable y
)

SELECT  c.ID,
        c.[DATE],
        c1.[DATE]
FROM cte c
LEFT JOIN cte c1 
    ON c.ID = c1.ID AND c.RN = c1.RN+1

Output:

ID          DATE        DATE
a2cVqAAl    6/16/2015   NULL
a2cVqAAl    6/24/2015   6/16/2015
a2cVqAAl    6/15/2015   6/24/2015
a36E8AAl    10/16/2015  NULL
a36E8AAl    7/8/2015    10/16/2015
d3yAAA      7/10/2015   NULL
d3yAAA      7/30/2015   7/10/2015
d3yAAA      9/9/2015    7/30/2015
d3yAAA      7/10/2015   9/9/2015
d3yAAA      7/14/2015   7/10/2015
d3yAAA      7/14/2015   7/14/2015


来源:https://stackoverflow.com/questions/39223109/sql-creating-a-new-column-with-previous-dates-in-new-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!