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

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

    Try something like this

    select country, food_id, count(*) cnt 
    into #tempTbl 
    from mytable 
    group by country, food_id
    
    select country, food_id
    from  #tempTbl as x
    where cnt = 
      (select max(cnt) 
      from mytable 
      where country=x.country 
      and food_id=x.food_id)
    

    This could be put all into a single select, but I don't have time to muck around with it right now.

    Good luck.

提交回复
热议问题