Postgresql – Have both distinct and count

postgresql

I have a table users(id and name) and order(cost and user: FK to users).

users.name users.id
bob               1
alice             1

and

orders.user orders.cost
          1          15
          1           5
          2           4
          1           4
          1           3
          1           3
          2           3

Here is a query which joints users and orders and sorts by order cost.

users.name users.id orders.user orders.cost
bob               1           1          15
alice             1           1           5
bob               2           2           4
alice             1           1           4
alice             1           1           3
alice             1           1           3
bob               2           2           3

If I were to do a distinct on user (in Postgresql), I would get

users.name    cost
bob              15
alice             5

I actually want the counts, while still being sorted on highest order cost/

users.name    count
bob               3
alice             4

Best Answer

Not sure I understand, but I guess something like:

select u.name, count(*)
from users u
join order o
    on u.id = o.user
group by u.name
order by max(o.cost) desc

would do. Please include your query and if relevant, table definitions for future questions.