Check this example too:
declare @table as table (day_of date, external_subscription_id varchar(20), plan_name varchar(20), status_type varchar(20))
insert @table values
( '04/23/2019 0:00', '304585LP', 'yearly', 'New Business ' ),
( '04/24/2019 0:00', '304585LP', 'yearly', 'Regular ' ),
( '04/25/2019 0:00', '304585LP', 'yearly', 'Regular ' ),
( '10/20/2020 0:00', '304585LP', 'yearly', 'cancelled ' ),
( '01/04/2017 0:00', 'OPK6518 ', 'monthly', 'Reactivation ' ),
( '01/24/2020 0:00', 'OPK6518 ', 'monthly', 'regular ' ),
( '01/25/2020 0:00', 'OPK6518 ', 'monthly', 'regular ' ),
( '06/22/2020 0:00', 'OPK6518 ', 'monthly', 'cancelled ' ),
( '03/01/2018 0:00', '4598KCP ', 'weekly', 'New Business ' ),
( '03/02/2018 0:00', '4598KCP ', 'weekly', 'regular ' ),
( '03/03/2018 0:00', '4598KCP ', 'weekly', 'regular ' ),
( '03/04/2018 0:00', '4598KCP ', 'weekly', 'regular ' ),
( '12/05/2018 0:00', '4598KCP ', 'weekly', 'cancelled ' ),
( '07/15/2020 0:00', '458CPLK ', 'quarterly', 'Reactivation' ),
( '07/16/2020 0:00', '458CPLK ', 'quarterly', 'Reactivation' ),
( '07/17/2020 0:00', '458CPLK ', 'quarterly', 'Reactivation' ),
( '07/18/2020 0:00', '458CPLK ', 'quarterly', 'Reactivation' ),
( '07/19/2020 0:00', '458CPLK ', 'quarterly', 'Reactivation' ),
( '08/20/2020 0:00', '458CPLK ', 'quarterly', 'cancelled ' ),
( '03/04/2020 0:00', 'ZIPC25UP', 'monthly', 'Reactivation ' ),
( '03/05/2020 0:00', 'ZIPC25UP', 'monthly', 'regular ' ),
( '03/06/2020 0:00', 'ZIPC25UP', 'monthly', 'Regular ' ),
( '06/22/2020 0:00', 'ZIPC25UP', 'monthly', 'cancelled ' )
select * from @table
---
;
with
Q1 as
(
select *, ROW_NUMBER() over (partition by external_subscription_id, plan_name order by day_of) as rn
from @table
where status_type in ('New Business', 'Reactivation', 'cancelled')
),
Q2 as
(
select *, DATEDIFF(d, day_of, LEAD(day_of) over (partition by external_subscription_id, plan_name order by rn)) as d
from Q1
where rn = 1 or status_type = 'cancelled'
),
Q3 as
(
select plan_name, status_type, sum(d) as [day range]
from Q2
where status_type in ('New Business', 'Reactivation')
group by plan_name, status_type
)
select
(select max(day_of) from @table as t where t.plan_name = Q3.plan_name) as day_of,
*
from Q3
order by day_of
/*
day_of plan_name status_type day range
---------- -------------------- -------------------- -----------
2018-12-05 weekly New Business 279
2020-06-22 monthly Reactivation 1375
2020-08-20 quarterly Reactivation 36
2020-10-20 yearly New Business 546
*/