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

前端 未结 9 1577
生来不讨喜
生来不讨喜 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 02:59

    Here is a statement which I believe gives you what you want and is simple and concise:

    select distinct on (country) country, food_id
    from munch
    group by country, food_id
    order by country, count(*) desc
    

    Please let me know what you think.

    BTW, the distinct on feature is only available in Postgres.

    Example, source data:

    country | food_id | eaten
    US        1         2017-1-1
    US        1         2017-1-1
    US        2         2017-1-1
    US        3         2017-1-1
    GB        3         2017-1-1
    GB        3         2017-1-1
    GB        2         2017-1-1
    

    output:

    country | food_id
    US        1
    GB        3
    

提交回复
热议问题