PSQL ordering by 1 column but keeping another column grouped
How do I order a table by one column (i.e. id
) while keeping rows grouped together based on another column (i.e. name
)?
In my example I would like the query to return rows ordered by id DESC
first but maintain grouping the rows by name.
Table:
id | name
---+---------
1 | bob
3 | charles
2 | bob
4 | charles
5 | alice
6 | bob
7 | alice
8 | bob
Desired output:
id | name
---+---------
8 | bob
6 | bob
2 | bob
1 | bob
7 | alice
5 | alice
4 | charles
3 | charles
Solution 1:
You can try this:
select * from table_name
order by max(id) over(partition by name) desc, id desc
The names with the biggest max(id)
will come first, ordered by id desc
.
Fiddle