Reset Row Number On Value Change, But With Repeat Values In Partition
Solution 1:
This is a gaps and islands problem, and we can use the difference in row numbers method here:
WITH cte AS (
SELECT*,
ROW_NUMBER() OVER (PARTITIONBY custno ORDERBY moddate) rn1,
ROW_NUMBER() OVER (PARTITIONBY custno, who ORDERBY moddate) rn2
FROM chr
)
SELECT custno, moddate, who,
ROW_NUMBER() OVER (PARTITIONBY custno, rn1 - rn2 ORDERBY moddate) rn
FROM cte
ORDERBY
custno,
moddate;
Demo
For an explanation of the difference in row number method used here, rn1 is just a time-ordered sequence from 1 onwards, per customer, according to the data you have shown above. The rn2 sequence is partitioned additionally by who. It is the case the difference between rn1 and rn2 will always have the same value, for each customer. It is with this difference that we then take a row number over the entire table to generate the sequence you actually want to see.
Solution 2:
The last ROW_NUMBER clause should be:
ROW_NUMBER() OVER (PARTITIONBY custno, who, rn1 - rn2 ORDERBY custno, moddate) rn
Try changing the second and fourth records to EMSZC49 and you'll see what I mean. You'll get the same issue anytime the first n who records match the next n who records.

Post a Comment for "Reset Row Number On Value Change, But With Repeat Values In Partition"