Reputation: 519
I deal with big job to find max period by FULL months of enrollment within the year (12 months period), which I did OK if we have 2 periods. Just got stuck at the end while testing if I have 3+ periods. Data below and picture hope will provide all information and easy start. Thanks to all. This is final work table I got at the end of my process, thanks all. Code below produces partially correct results. My global task find MAX period for each member, so some fields are just for easy working.
/*
DROP TABLE IF EXISTS #t;
CREATE TABLE #t ( Cust VARCHAR(10), mm INT, mm_prev INT, rn INT)
INSERT #t values
(123456, 1, NULL, 1), (123456, 2, 1, 2),
(123456, 4, 2, 3), (123456, 5, 4, 4), (123456, 6, 5, 5),
(123456, 8, 6, 6), (123456, 9, 8, 7), (123456, 10, 9, 8), (123456, 11, 10, 9), (123456, 12, 11, 10),
(777 , 1, NULL, 1),(777 , 2, 1, 2)
SELECT * from #t
*/
select
Cust, MIN(mm) mmStart, MAX(mm) mmEnd,
CASE WHEN mm = rn THEN 'Grp A' ELSE 'Grp B' END Grp
,COUNT(*) mm_count
FROM #t
WHERE 1=1
--mm - ISNULL(mm_prev,0) = 1 --check for conseq but we drop mm=6--> start of new period
-- AND mm = rn -- this brings only first group by mm
GROUP BY Cust, CASE WHEN mm = rn THEN 'Grp A' ELSE 'Grp B' END
ORDER BY 1,4
just for the case if somebody prefer to deal with initial raw data I posting it here too with some gap and islands:
CREATE TABLE #tr ( Cust varchar(10), ENR_START date, enr_END date, rn INT); -- SELECT * FROM #t
INSERT #tr VALUES
('123456' , '2018-12-01', '2019-3-1' , 1),
('123456' , '2019-3-28', '2019-6-30' , 2), -- 6 month with 2 periods, island
('123456' , '2019-7-26', '2019-8-20' , 3),
('123456' , '2019-8-15', '2019-12-31' , 4),
('777' , '2018-11-4', '2019-3-3' , 1)
select * from #tr
Screenshot is here:
Upvotes: 2
Views: 78
Reputation: 24793
looks to me, you wanted this. Not really sure what is the purpose of the case statement in your query
with cte as
(
SELECT *,
grp = mm - rn
from #t
)
SELECT Cust, MIN(mm) as mmStart, MAX(mm) as mmEnd, grp,
count(*) as mm_count
FROM cte
GROUP BY Cust, grp
order by Cust, mmStart
Upvotes: 1