stepson
Aged Yak Warrior
545 Posts |
Posted - 2015-04-07 : 08:55:04
|
[code];WITH cteSample AS( SELECT ID ,Date ,State FROM (VALUES (1, '20140101', 'Paying') ,(1, '20140201' ,'Paying') ,(1, '20140301' ,'Paying') ,(1, '20140401' ,'Paying') ,(1, '20140501' ,'Paying') ,(1, '20140601' ,'Cancelled') ,(1, '20140701' ,'Cancelled') ,(1, '20140801' ,'Cancelled') ,(1, '20140901' ,'Cancelled') ,(1, '20141001' ,'Paying') ,(1, '20141101' ,'Cancelled') ,(1, '20141201' ,'Cancelled') ,(1, '20150101' ,'Cancelled') ,(1, '20150201' ,'Paying') ,(1, '20150301','Paying') ,(1, '20150401' ,'Paying') ) A (ID,Date,State) ),cteFinalAS ( SELECT id, Date, State --,ROW_NUMBER()OVER(ORDER BY ID,Date) AS RN1 ,ROW_NUMBER()OVER(ORDER BY ID,Date) - ROW_NUMBER()OVER(PARTITION BY State ORDER BY ID,Date) AS Grp FROM cteSample --ORDER BY RN1 )SELECT ID ,MIN(Date) AS DateFrom ,MAX(Date) AS DateTo ,StateFROM cteFinalGROUP BY ID, State ,GrpORDER BY DateFrom[/code]the result set is:[code]ID DateFrom DateTo State1 20140101 20140501 Paying1 20140601 20140901 Cancelled1 20141001 20141001 Paying1 20141101 20150101 Cancelled1 20150201 20150401 Paying[/code]sabinWeb MCP |
|
|