| Author |
Topic |
|
KevMull
Starting Member
11 Posts |
Posted - 2009-10-02 : 06:05:21
|
| My table (tblVacation) records employees’ work leave/vacation as follows…Id(pk), empId, vacationDate 1, 007, 01/20/20092, 007, 01/21/20093, 007, 01/22/20094, 007, 01/25/20095, 007, 01/28/20096, 007, 01/29/20097, 008, 04/17/20098, 008, 04/18/20099, 008, 06/11/2009I need to created a view/sp that shows consecutive dates grouped as one record with the final date being the ‘end date’ in a new column, all in a single row. Single dates would also show but have the same start and end date.So based on the above table it would look something like…empId, startDate, endDate007, 01/20/2009, 01/22/2009007, 01/25/2009, 01/25/2009007, 01/28/2009, 01/29/2009008, 04/17/2009, 04/18/2009008, 06/11/2009, 06/11/2009Many Thanks |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2009-10-02 : 08:54:21
|
| this should give you a starthttp://weblogs.sqlteam.com/peterl/archive/2009/08/12/Another-running-streaks-algorithm.aspx |
 |
|
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2009-10-02 : 08:56:16
|
[code]DECLARE @sample TABLE( Id int, empId varchar(3), vacationDate datetime)INSERT INTO @sampleSELECT 1, '007', '01/20/2009' UNION ALLSELECT 2, '007', '01/21/2009' UNION ALLSELECT 3, '007', '01/22/2009' UNION ALLSELECT 4, '007', '01/25/2009' UNION ALLSELECT 5, '007', '01/28/2009' UNION ALLSELECT 6, '007', '01/29/2009' UNION ALLSELECT 7, '008', '04/17/2009' UNION ALLSELECT 8, '008', '04/18/2009' UNION ALLSELECT 9, '008', '06/11/2009'; WITH data (empId, vacationDate, seqNo)AS( SELECT empId, vacationDate, seqNo = row_number() OVER (PARTITION BY empId ORDER BY vacationDate) FROM @sample),r_cteAS( -- anchor member SELECT empId, vacationDate, seqNo, startDate = vacationDate FROM data WHERE seqNo = 1 UNION ALL -- recursive member SELECT d.empId, d.vacationDate, d.seqNo, startDate = CASE WHEN c.vacationDate = DATEADD(DAY, -1, d.vacationDate) THEN c.startDate ELSE d.vacationDate END FROM r_cte c INNER JOIN data d ON c.empId = d.empId AND c.seqNo = d.seqNo - 1)SELECT empId, startDate, endDate = MAX(vacationDate)FROM r_cteGROUP BY empId, startDate/*empId startDate endDate ----- ----------- -----------007 2009-01-20 2009-01-22 007 2009-01-25 2009-01-25 007 2009-01-28 2009-01-29 008 2009-04-17 2009-04-18 008 2009-06-11 2009-06-11 (5 row(s) affected)*/[/code] KH[spoiler]Time is always against us[/spoiler] |
 |
|
|
|
|
|