我有一张这样的桌子:
Column | Type | Modifiers
---------+------+-----------
country | text |
food_id | int |
eaten | date |
对于每个国家,我都想获得最常吃的食物。我能想到的最好的(我正在使用 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;
在最后一条语句中,需要 GROUP BY 和 max() 来打破关系,其中两种不同的食物具有相同的计数。
对于概念上简单的东西,这似乎需要做很多工作。有没有更直接的方法来做到这一点?