我正在选择 group by 和 count 中使用的列,查询看起来像
SELECT s.country, count(*) AS posts_ct
FROM store s
JOIN store_post_map sp ON sp.store_id = s.id
GROUP BY 1;
但是,我想从存储表中选择更多字段,例如商店名称或商店地址,其中 count 为最大,但我不将其包含在 group by 子句中。
我正在选择 group by 和 count 中使用的列,查询看起来像
SELECT s.country, count(*) AS posts_ct
FROM store s
JOIN store_post_map sp ON sp.store_id = s.id
GROUP BY 1;
但是,我想从存储表中选择更多字段,例如商店名称或商店地址,其中 count 为最大,但我不将其包含在 group by 子句中。
例如,要获得每个国家/地区发布次数最多的商店:
SELECT DISTINCT ON (s.country)
s.country, s.store_id, s.name, sp.post_ct
FROM store s
JOIN (
SELECT store_id, count(*) AS post_ct
FROM store_post_map
GROUP BY store_id
) sp ON sp.store_id = s.id
ORDER BY s.country, sp.post_ct DESC
将任意数量的列添加store
到SELECT
列表中。
此相关答案中有关此查询样式的详细信息:
这会产生每个国家/地区的计数并选择具有最高后计数的商店(之一):
SELECT DISTINCT ON (s.country)
s.country, s.store_id, s.name
,sum(post_ct) OVER (PARTITION BY s.country) AS post_ct_for_country
FROM store s
JOIN (
SELECT store_id, count(*) AS post_ct
FROM store_post_map
GROUP BY store_id
) sp ON sp.store_id = s.id
ORDER BY s.country, sp.post_ct DESC;
这是有效的,因为在每个定义sum()
之前应用了窗口函数。DISTINCT ON