Last active
March 20, 2019 17:19
-
-
Save mburbea/e216a5a2d11d4dbae5919b682b7f0d85 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--drop table if exists #seq | |
--;with t(date,status) as ( | |
-- select convert(date,dateadd(d,row_number() over (order by @@dbts),{d'2018-12-31'})) | |
-- ,abs(sign(BINARY_CHECKSUM(newid())%2)) | |
--from string_split(REPLICATE('1,',30),',') a | |
--) | |
--select * into #seq from t | |
select s1.date | |
,s1.status | |
,datediff(d,isnull(last_one,min_d),s1.date) successive_days | |
from #seq s1 | |
outer apply ( | |
select top 1 s2.date | |
from #seq s2 | |
where s1.date >=s2.date | |
and s2.status = 1 | |
order by s2.date desc) f(last_one) | |
cross join ( | |
select dateadd(d,-1,min(date)) | |
from #seq) q(min_d) | |
select date | |
,status | |
,(1^status) * row_number() over (partition by pkey order by date) | |
from ( | |
select date | |
,status | |
,sum(change_event) over (order by date) pkey | |
from ( | |
select date | |
,status | |
,1 + 0 * nullif(s1.status,lag(s1.status) over (order by date)) change_event | |
from #seq s1 | |
) q | |
) q | |
order by date |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment