0

I have a table with data something like below:

| ID(pk) | name | count |
|--------|------|-------|
| id1    | xyz  |    98 |
| id2    | ptr  |     5 |
| id3    | xyz  |     2 |
| id4    | de   |     1 |
| id5    | ptr  |     1 |

I want to first have the row with max count then all the rows with same name sorted by count. After that next max count and all the counts with same name. Something like below:

| ID(pk) | name | count |
|--------|------|-------|
| id1    | xyz  |    98 |
| id3    | xyz  |     2 |
| id2    | ptr  |     5 |
| id5    | ptr  |     1 |
| id4    | de   |     1 |

Is something like this possible in Postgres?

1
  • Your expected result doesn't match your description ("first sort by count desc but then the duplicate name count").
    – mustaccio
    Commented Jun 20 at 12:08

1 Answer 1

2

It seems you want to order by the maximum count for the same name first - which can be achieved with a basic window function.

SELECT *
FROM   tbl
ORDER  BY max(count) OVER (PARTITION BY name) DESC, count DESC;

fiddle

Notably, the window function also works in the ORDER BY clause as demonstrated.

1
  • Thanks a lot. This was exactly what I was looking for - a window function.
    – gmtek
    Commented Jun 21 at 5:48

Not the answer you're looking for? Browse other questions tagged or ask your own question.