Mich28
Mich28

Reputation: 519

T-SQL: process consequtive periods and count by group

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

Screenshot is here:

enter image description here

Upvotes: 2

Views: 78

Answers (1)

Squirrel
Squirrel

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

Related Questions