The example table:
id | name | create_time | group_id |
---|---|---|---|
1 | a | 2022-01-01 12:00:00 | group1 |
2 | b | 2022-01-01 13:00:00 | group1 |
3 | c | 2022-01-01 12:00:00 | NULL |
4 | d | 2022-01-01 13:00:00 | NULL |
5 | e | NULL | group2 |
I need to get top 1 rows (with the minimal create_time
) grouped by group_id
with these conditions:
create_time
can be null - it should be treated as a minimal valuegroup_id
can be null - all rows with nullablegroup_id
should be returned (if it's not possible, we can usecoalesce(group_id, id)
or sth like that assuming that ids are unique and never collide with group ids)- it should be possible to apply pagination on the query (so join can be a problem)
- the query should be universal as much as possible (so no vendor-specific things). Again, if it's not possible, it should work in MySQL 5&8, PostgreSQL 9+ and H2
The expected output for the example:
id | name | create_time | group_id |
---|---|---|---|
1 | a | 2022-01-01 12:00:00 | group1 |
3 | c | 2022-01-01 12:00:00 | NULL |
4 | d | 2022-01-01 13:00:00 | NULL |
5 | e | NULL | group2 |
I've already read similar questions on SO but 90% of answers are with specific keywords (numerous answers with PARTITION BY
like https://stackoverflow.com/a/6841644/5572007) and others don't honor null values in the group condition columns and probably pagination (like https://stackoverflow.com/a/14346780/5572007).