I have following data
GROUP_ID INDEX
NULL 1
1 2
NULL 3
1 4
NULL 5
2 6
2 7
What I want is to get a field that contains:
- if group_id IS NOT NULL, a smallest index in that group
- if group_id IS NULL, then index from that row
The result dataset for the above example would be:
GROUP_ID INDEX GROUP_INDEX_MIN
NULL 1 1
1 2 2
NULL 3 3
1 4 2
NULL 5 5
2 6 6
2 7 6
In Oracle I would resolve this by using (CASE WHEN group_id IS NOT NULL THEN MIN(index) OVER (PARTITION BY group_id) ELSE group_id END), but since MySQL does not support that, I really don’t know how to proceed 🙂 I can solve this by using a subquery that retrieves minimal values for each group and then left joining to it, but I think that there must be a more elegant solution.
If you need any more information, please ask.
Thanks.
Just create an inline view representing the min Group_index_min (minT) and then join to it and do a coalesce between group_ID and the min