【发布时间】:2010-09-25 13:43:19
【问题描述】:
我有一张这样的桌子:
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() 来打破关系,其中两种不同的食物具有相同的计数。
对于概念上简单的事情,这似乎需要做很多工作。有没有更直接的方法?
【问题讨论】:
标签: sql postgresql greatest-n-per-group