Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Group by event using row_number

I have this table:

CREATE TABLE #Data 
(
    Event_Date date,
    Person_ID varchar(1), 
    Event_flag varchar(1)
)

INSERT INTO #Data (Event_date, Person_ID, Event_flag)
VALUES
    ('20190910', 'A', 'X'),
    ('20190911', 'A', 'X'),
    ('20190912', 'A', 'Y'),
    ('20190913', 'A', 'X'),
    ('20190914', 'A', 'X'),
    ('20190915', 'A', 'X'),
    ('20190916', 'A', 'Y')

How to get result using row_number or loop, to get same row_numbers by the same event, just on other event row_number get +1

Person_ID   Event_flag  Rn
--------------------------
A           X           1
A           X           1
A           Y           2
A           X           3
A           X           3
A           X           3
A           Y           4

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Appreciate that the counter in the expected Rn column should increment by one each time the event flag changes value, for a given person, as ordered by the event date. We can use LAG here to construct an increment column, which when summed by event date, will generate the sequence you want.

WITH cte AS (
    SELECT *, CASE WHEN Event_flag =
              LAG(Event_flag) OVER (PARTITION BY Person_ID ORDER BY Event_date)
                   THEN 0 ELSE 1 END AS flag
    FROM Data
)

SELECT Event_date, Person_ID, Event_flag,
       SUM(flag) OVER (ORDER BY Event_date) AS Rn
FROM cte
ORDER BY Event_date;

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading