我有一个类似这样的表:
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()函数来解决两种不同食品计数相同时的竞争关系。
这看起来为了一个概念上简单的东西而付出了很多工作。有没有更直接的方法呢?