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 |
jay83091
Starting Member
14 Posts |
Posted - 2011-06-06 : 00:02:33
|
Hi Experts,I am trying to get the start date and end date based on the date ranking. i.e. based on the date ranking, return the start date and end dates.If first date is 31/05/2010 and 2nd ranked date is 30/06/2010 then start date willb e 31/05/2010 and end date will be 29/06/2010.I got up to doing the ranking but can't really get the start, end date columns.Please help T_TSource data contains dates and ID.Date ID31/05/2010 5731/05/2010 5730/06/2010 5731/07/2010 5731/08/2010 5730/09/2010 5731/10/2010 5731/12/2010 5731/01/2011 5731/03/2011 5730/04/2011 5731/05/2011 5731/05/2010 400431/07/2010 400430/11/2010 400430/04/2011 4004Desired OutputDate ID RANK Effective Start Effective End31/05/2010 57 1 31/05/2010 29/06/201031/05/2010 57 1 31/05/2010 29/06/201030/06/2010 57 3 30/06/2010 30/07/201031/07/2010 57 4 31/07/2010 30/08/201031/08/2010 57 5 31/08/2010 29/09/201030/09/2010 57 6 30/09/2010 30/09/201031/10/2010 57 7 31/10/2010 30/11/201031/12/2010 57 8 31/12/2010 30/01/201131/01/2011 57 9 31/01/2011 30/03/201131/03/2011 57 10 31/03/2011 29/04/201130/04/2011 57 11 30/04/2011 30/05/201131/05/2011 57 12 31/05/2011 31/12/999931/05/2010 4004 1 31/05/2010 30/07/201031/07/2010 4004 2 31/07/2010 29/11/201030/11/2010 4004 3 30/11/2010 29/04/201130/04/2011 4004 4 30/04/2011 31/12/9999 |
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2011-06-06 : 03:48:01
|
[code]; withcte as( select *, row_no = row_number() over (partition by ID order by DATE) from yourtable)select c1.DATE, c1.ID, start_date = c1.DATE, end_date = isnull(dateadd(day, -1, c2.DATE), '9999-12-31')from cte c1 left join cte c2 on c1.ID = c2.ID and c1.row_no = c2.row_no - 1[/code] KH[spoiler]Time is always against us[/spoiler] |
 |
|
jay83091
Starting Member
14 Posts |
Posted - 2011-06-06 : 19:19:45
|
You are the best khtan |
 |
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2011-06-06 : 21:20:51
|
you are welcome KH[spoiler]Time is always against us[/spoiler] |
 |
|
|
|
|
|
|