Click here to Skip to main content
15,392,442 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am new to SQL and stuck in a problem where i have to fetch values in below way:
existing datatable
ID | Date
01 | 3/3/17
02 | 4/3/17
03 | 8/3/17
04 | 1/4/17


I want the data should be selected in below way:

ID  | Date1  | Date2
01  | 3/3/17 | 4/3/17 
02  | 4/3/17 | 8/3/17
03  | 8/3/17 | 1/4/17
04  | 1/4/17 | null


Please guide me SQL query to select above way.

What I have tried:

from some link I tried:

SQL
SELECT A.Id , 
               A.Date AS CurDate , 
               B.Date AS NxtDate 
FROM words AS A
LEFT JOIN words AS B ON A.Date < B.Date 


(ID will be GUID, so I have not consider Id in any condition)
This is not giving expected result..
Posted
Updated 16-Jul-18 22:39pm
v3
Comments
kmoorevs 16-Jul-18 11:34am
   
Is that last date correct? (or should it be 2018) If the dates should be ordered ascending you can use subqueries to do what you want. If so, I can provide an example that works.

Looking at your expected data it would appear to be in Date order. You can assign a row number on that basis which replaces the ID used in Solution 1 (and would therefore work with a GUID as the ID) e.g.
SQL
DECLARE @Table TABLE (ID INT IDENTITY(1,1) NOT NULL, TheDate DATE)

INSERT @Table(TheDate) 
values ('03-MAR-2017'), ('04-MAR-2017'), ('08-MAR-2017'), ('01-APR-2017')
;WITH CTE AS
(
    SELECT ID, TheDate
    ,ROW_NUMBER() OVER(ORDER BY TheDate) AS rn
    FROM @Table
)
SELECT CTE.ID, CTE.TheDate As Date1, NXT.TheDate As Date2
FROM CTE
LEFT OUTER JOIN CTE NXT ON NXT.rn = CTE.rn + 1
If you have SQL Server 2012 (not the Express version) or a later version (including 2014 Express), then you can use Window functions instead (far neater)
SQL
SELECT ID, TheDate, LEAD(TheDate,1) OVER (ORDER BY TheDate) FROM @Table
   
Comments
ali khanna 17-Jul-18 5:00am
   
Thanks
Richard Deeming 17-Jul-18 11:39am
   
"SQL Server 2012 (not the Express version)"

LEAD and LAG work fine in SQL 2012 Express.
CHill60 17-Jul-18 12:23pm
   
Great news, cheers. It's been a while since I looked but I was sure that quote was from the M$ documentation - I wasn't in a position to prove it either way at the time. Guess I'd better update my article that quotes it! (at some stage)
This works with your current data; however, you are on your own if you switch to a GUID

SQL
DECLARE @Table TABLE (ID INT IDENTITY(1,1) NOT NULL, TheDate DATE)

INSERT @Table(TheDate) 
values ('03/03/2017'), ('04/03/2017'), ('08/03/2017'), ('01/04/2017')

SELECT a.ID
     , Date1 = a.TheDate
     , Date2 = b.TheDate

FROM            @Table  a
LEFT OUTER JOIN @Table  b ON a.ID + 1 = b.ID

ORDER BY A.ID
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900