Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
AskSQLTeam
Ask SQLTeam Question
0 Posts |
Posted - 2007-02-14 : 08:36:09
|
Rama Prasad writes "Hi ExpertsNeed an advise from you, I have a table with data:ID Transaction1 01-Jan-20071 02-Jan-20071 03-Jan-20072 10-Jan-20072 11-Jan-2007I want to write a SQL Statement whose output to be:ID Previous Date Next Date1 01-Jan-2007 02-Jan-20071 02-Jan-2007 03-Jan-20072 10-Jan-2007 11-Jan-2007Can you please Help?Thankyou in advance" |
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2007-02-14 : 09:03:19
|
[code]declare @table table( [ID] int, [Transaction] datetime)insert into @tableselect 1, '01-Jan-2007' union allselect 1, '02-Jan-2007' union allselect 1, '03-Jan-2007' union allselect 2, '10-Jan-2007' union allselect 2, '11-Jan-2007'select p.[ID], p.[Transaction] as [Previous Date], min(n.[Transaction]) as [Next Date]from @table p inner join @table n on p.ID = n.ID and p.[Transaction] < n.[Transaction]group by p.[ID], p.[Transaction]/*ID Previous Date Next Date ----------- ------------------- -----------1 2007-01-01 2007-01-02 1 2007-01-02 2007-01-03 2 2007-01-10 2007-01-11 */[/code] KH |
 |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2007-02-14 : 09:33:03
|
[code]select t1.id, t1.[transaction], t2.[transaction]from @table as t1left join @table as t2 on t2.id = t1.id and t2.[transaction] - 1 = t1.[transaction]where t2.id is not nullorder by 1, 2[/code]Peter LarssonHelsingborg, Sweden |
 |
|
|
|
|
|
|