I have the following table:
day | name | val |
---|---|---|
12-01-2021 | Een | 1 |
11-01-2021 | Twee | 12 |
12-01-2021 | Drie | 0 |
12-01-2021 | Twee | 1 |
11-01-2021 | Drie | 19 |
11-01-2021 | Een | 11 |
Now I want to get the max val
per day, including the name of the corresponding val
. How can I get this? I got to the following query:
select max(val), day
from table t
group by day;
However, I want the result to include the corresponding name. My first idea was to include name
in the query:
select name, max(val), day
from table t
group by day;
The problem is that Postgres wants me to also group by name, which again results in the table above (in a different order of rows).
Use distinct on
:
select distinct on (day) t.*
from t
order by day, val desc;