Get most common value for each value of another column in SQL

前端 未结 9 1574
生来不讨喜
生来不讨喜 2020-11-30 02:29

I have a table like this:

 Column  | Type | Modifiers 
---------+------+-----------
 country | text | 
 food_id | int  | 
 eaten   | date | 
<
9条回答
  •  北海茫月
    2020-11-30 03:10

    It is now even simpler: PostgreSQL 9.4 introduced the mode() function:

    select mode() within group (order by food_id)
    from munch
    group by country
    

    returns (like user2247323's example):

    country | mode
    --------------
    GB      | 3
    US      | 1
    

    See documentation here: https://wiki.postgresql.org/wiki/Aggregate_Mode

    https://www.postgresql.org/docs/current/static/functions-aggregate.html#FUNCTIONS-ORDEREDSET-TABLE

提交回复
热议问题