I have a subquery with a column named code
that only has 1 and 0 values and an ID
column because I query a lot of codes for each ID. I want to group by said column (and by ID
) and by ocurrence but want to ignore groups with less than 3 records, so that bigger groups get merged.
I use ROW_NUMBER() - ROW_NUMBER() over (partition ...)
to generate a group number which I use to group records by, but sometimes the records get mixed up caused by a coincidence in the sequence of the row number and the partitioned row number. This is an example
code | row_number | row_number_partition_by_code | group_number
------------------------------------------------------------------
0 | 1 | 1 | 0
0 | 2 | 2 | 0
1 | 3 | 1 | 2
1 | 4 | 2 | 2
0 | 5 | 3 | 2
1 | 6 | 3 | 3
0 | 7 | 4 | 3
0 | 8 | 5 | 3
0 | 9 | 6 | 3
0 | 10 | 7 | 3
1 | 11 | 4 | 7
0 | 12 | 1 | 0
As you can see, some groups contain both codes!
After this, I do
GROUP BY group_number
HAVING COUNT(1) > 2
to eliminate small groups, and generate another group number to merge adjacent groups.
How can I group these values homogeneously?
More Details
All records are ordered by ID
and by date (the later in descending order) in every ROW_NUMBER()
.
The final result I expect is the time in minutes of the latest code group for each ID
, and merging groups that are separated by less than 3 minutes.
I'm more interested in the groups with the value 1, so if the latest code group is a 0 ( considering it is not a couple minutes long ) then ignore that ID
completely.
Usually, there is one record per minute. Sometimes it can take hours without a record for any ID
SELECT ... FROM ( SELECT ... FROM (...) tTwo ) tThree ...
First select assigns a code to every row. Second select creates a group number for every row. Third select groups by that group number, filters groups with less than 3 records and generates another group number. Fourth select groups by again (merging adjacent groups)