With the below data example I want to group by the groupcol
and within the group order by the val
col and if no val exists secondary order by the ID
.
Understand the first MAX value (sql below) but how to achieve the secondary MAX if no VAL exists?
SELECT ID,MAX(VAL), GROUPCOL FROM table GROUP BY GROUPCOL
ID | VAL | GROUPCOL |
---|---|---|
1 | 10 | 1 |
2 | 2 | |
3 | 2 | |
4 | 3 | |
5 | 3 | |
6 | 9 | 1 |
7 | 1 |
Would like to return this
ID | VAL | GROUPCOL |
---|---|---|
1 | 10 | 1 |
3 | 2 | |
5 | 3 |
2
Answers
You need to specify which value you want to return for the column
ID
, after you group byGROUPCOL
. MySQL has the choice to return either one of the values1,6,7
for GROUPCOL=1. you should specifyMIN()
when you want 1, or MAX when you want to return 7.But when you say: "I want to group by the groupcol and within the group order by the val col and if no val exists secondary order by the ID.", you have to do something like:
output:
see: DBFIDDLE
This is a typical use-case for row_number
DbFiddle example