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

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

提交回复
热议问题