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

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

    SELECT country, MAX( food_id )
      FROM( SELECT m1.country, m1.food_id
              FROM munch m1
             INNER JOIN ( SELECT country
                               , food_id
                               , COUNT(*) as food_counts
                            FROM munch m2
                        GROUP BY country, food_id ) as m3
                     ON m1.country = m3.country
             GROUP BY m1.country, m1.food_id 
            HAVING COUNT(*) / COUNT(DISTINCT m3.food_id) = MAX(food_counts) ) AS max_foods
      GROUP BY country
    

    I don't like the MAX(.) GROUP BY to break ties... There's gotta be a way to incorporate eaten date into the JOIN in some way to arbitrarily select the most recent one...

    I'm interested on the query plan for this thing if you run it on your live data!

提交回复
热议问题