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

前端 未结 9 1591
生来不讨喜
生来不讨喜 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:11

    Here's how to do it without any temp tables:

    Edit: simplified

    select nf.country, nf.food_id as most_frequent_food_id
    from national_foods nf
    group by country, food_id 
    having
      (country,count(*)) in (  
                            select country, max(cnt)
                            from
                              (
                              select country, food_id, count(*) as cnt
                              from national_foods nf1
                              group by country, food_id
                              )
                            group by country
                            having country = nf.country
                            )
    

提交回复
热议问题