I would like to insert a row number that is partitioned by the previous flag.
I have tried using the lag function within the partition, but am having challenges with NULLs.
I can determine the different block of X's by multiple date differences determined by the LAG and LEAD function and other key flags. So each 0 in the LAG and LEAD columns indicate that the rows are "linked."
My table looks like this and I want the row number to restart at the second block of X's:
Person_ID Event_flag Row_number LAG_datediff LEAD_datediff FLAG FLAG2
A X 1 NULL 0 1 NULL
A X 2 0 40 NULL NULL
A Y 1 40 150 NULL NULL
A X 1 150 0 1 NULL
A X 2 0 NULL NULL 1
You need an ordering column to number rows. It's difficult without sample data, but if your table is ordered by one date
column, the next approach may help to get your expected results:
Data:
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')
Statement:
;WITH ChangesCTE AS (
SELECT
Event_Date,
Person_ID,
Event_flag,
CASE
WHEN Event_flag = LAG(Event_flag) OVER (ORDER BY Event_Date) THEN 0
ELSE 1
END AS Change_ID
FROM #Data
), GroupsCTE AS (
SELECT
Event_Date,
Person_ID,
Event_flag,
SUM([Change_ID]) OVER (ORDER BY Event_Date) AS Group_ID
FROM ChangesCTE
)
SELECT
Person_ID,
Event_flag,
ROW_NUMBER() OVER (PARTITION BY Group_ID ORDER BY Event_Date) AS Rn
FROM GroupsCTE
Output:
--------------------------
Person_ID Event_flag Rn
--------------------------
A X 1
A X 2
A Y 1
A X 1
A X 2
A X 3
A Y 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.