我正在学习PostgreSQL,正在努力解决这个问题。
我已经设置了一个olympics表,正在查询并返回结果。我正在查询国家和赢得的金牌数,如下所示:

SELECT country, golds
FROM (SELECT distinct country, sum(gold_medals) as golds
      FROM olympics where year >= 2000 group by country
     ) foo
WHERE (golds < 10)
ORDER BY golds desc limit 10;

这准确地返回:
   country   | golds
-------------+-------
 Turkey      |     9
 Bulgaria    |     8
 Azerbaijan  |     6
 Estonia     |     6
 Georgia     |     6
 North Korea |     6
 Thailand    |     6
 Nigeria     |     6
 Uzbekistan  |     5
 Lithuania   |     5

我需要把这次获得同样数量金牌的国家(立陶宛和乌兹别克斯坦各5枚,所有国家各6枚)还给我。
我该怎么做呢?

最佳答案

@ErwinBrandstetter的解决方案是有效的,但为了完整起见,我还将抛出array_agg版本,该版本返回在单个单元格中作为字符串数组聚合在一起的国家:

WITH golds as (
    select
        sum(gold_medals) golds,
        country
    from olympics
    where year >= 2000
    group by country
    )

select
    golds,
    array_length(array_agg(country),1) n_countries,
    array_agg(country) countries
from golds
group by golds
having array_length(array_agg(country),1) > 1
order by golds asc

-- golds , n_countries , countries
--   5   ,     2       , '{lithuania,uzbekistan}'
--   6   ,     6       , '{thailand,"north korea",azerbaijan,nigeria,estonia,georgia}'

10-04 21:35