Ryan Gomes
Ryan Gomes

Reputation: 75

SQL Creating a new column with previous dates in new column

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

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

enter image description here

Or this link https://i.sstatic.net/2NRn1.jpg

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

Upvotes: 1

Views: 1426

Answers (2)

gofr1
gofr1

Reputation: 15977

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

Upvotes: 1

Ahmad Aghazadeh
Ahmad Aghazadeh

Reputation: 17131

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

Upvotes: 1

Related Questions