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

前端 未结 9 1576
生来不讨喜
生来不讨喜 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
                            )
    
    0 讨论(0)
  • 2020-11-30 03:12
    select country,food_id, count(*) ne  
    from   food f1  
    group by country,food_id    
    having count(*) = (select max(count(*))  
                       from   food f2  
                       where  country = f1.country  
                       group by food_id)  
    
    0 讨论(0)
  • 2020-11-30 03:15
    SELECT DISTINCT
    "F1"."food",
    "F1"."country"
    FROM "foo" "F1"
    WHERE
    "F1"."food" =
        (SELECT "food" FROM
            (
                SELECT "food", COUNT(*) AS "count"
                FROM "foo" "F2" 
                WHERE "F2"."country" = "F1"."country" 
                GROUP BY "F2"."food" 
                ORDER BY "count" DESC
            ) AS "F5"
            LIMIT 1
        )
    

    Well, I wrote this in a hurry and didn't check it really well. The sub-select might be pretty slow, but this is shortest and most simple SQL statement that I could think of. I'll probably tell more when I'm less drunk.

    PS: Oh well, "foo" is the name of my table, "food" contains the name of the food and "country" the name of the country. Sample output:

       food    |  country   
    -----------+------------
     Bratwurst | Germany
     Fisch     | Frankreich
    
    0 讨论(0)
提交回复
热议问题