Consider the following table:
Column_A | Column_B | Column_C |
---|---|---|
1 | UserA | NULL |
2 | UserB | NULL |
3 | UserC | 1 |
4 | UserA | 1 |
5 | UserB | NULL |
6 | UserB | 2 |
7 | UserC | 2 |
I'd like to return all rows (Column_A, Column_B, Column_C) such that either:
- Column_C is NULL, or
- for every unique value in Column_C, return the first row with Column_B == UserA. If no such row exists, return the first row sorted by Column_B.time_created.
Column_A | Column_B (FK) | Column_C |
---|---|---|
1 | UserA | NULL |
2 | UserB | NULL |
4 | UserA | 1 |
5 | UserB | NULL |
6 | UserB | 2 |
Not sure how to do this in a single query.
select
Column_A,
Column_B,
Column_C,
min(case when Column_B = UserA then 0 else 1 end) as custom_order
from Table
where Column_B in (UserA, UserB, UserC)
group by Column_C, Column_A
order by Column_C nulls first, custom_order;
The min clause doesn't de-dupe as expected.