我有这样一张桌子:
Column | Type | Modifiers
---------+------+-----------
country | text |
food_id | int |
eaten | date |
Run Code Online (Sandbox Code Playgroud)
对于每个国家,我想获得最常吃的食物.我能想到的最好的(我使用的是postgres)是:
CREATE TEMP TABLE counts AS
SELECT country, food_id, count(*) as count FROM munch GROUP BY country, food_id;
CREATE TEMP TABLE max_counts AS
SELECT country, max(count) as max_count FROM counts GROUP BY country;
SELECT country, max(food_id) FROM counts
WHERE (country, count) IN (SELECT * from max_counts) GROUP BY country;
Run Code Online (Sandbox Code Playgroud)
在最后一个陈述中,需要GROUP BY和max()来打破关系,其中两种不同的食物具有相同的数量.
对于概念上简单的事情来说,这似乎是很多工作.有没有更直接的方式来做到这一点?