简体   繁体   中英

Next row value in next column in SQL Server

How to display next row value in the current row as next column in SQL Server?

Mast table

 ID  Name
 ---------
 1   XYZ
 2   abc
 3   MNO

Detail table

 ID  Date
 -------------
 1   1/1/2019
 1   1/2/2019
 2   2/2/2019
 2   3/3/2019
 2   3/4/2019
 3   2/2/2019
 3   4/2/2019

I need the result to look like this:

    ID  Date      Next Date
    ------------------------
    1   1/1/2019   1/2/2019
    1   1/2/2019   NULL
    2   2/2/2019   3/3/2019
    2   3/3/2019   3/4/2019
    2   3/4/2019   NULL
    3   2/2/2019   4/2/2019
    3   4/2/2019   NULL

Use lead() window analytic function

select ID, Date, lead(Date) over (partition by ID Order by Date) as Next_Date
  from Detail

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM