我有一个看起来像这样的表:
control=# select * from animals;
age_range | weight | species
-----------+--------+---------
0-9 | 1 | lion
0-9 | 2 | lion
10-19 | 2 | tiger
10-19 | 3 | horse
20-29 | 2 | tiger
20-29 | 2 | zebra
我执行一个查询,汇总年龄范围组内动物的体重,我只想返回具有以上汇总权重的行 一定数量。
汇总查询:
SELECT
age_range,
SUM(animals.weight) AS weight,
COUNT(DISTINCT animals.species) AS distinct_species
FROM animals
GROUP BY age_range
HAVING SUM(animals.weight) > 3;
总结结果:
age_range | weight | distinct_species
-----------+--------+------------------
10-19 | 5 | 2
20-29 | 4 | 2
现在问题来了。除了这个摘要,我还想报告用于创建上述摘要行集的物种的不同数量作为一个整体。为简单起见,我们将此数字称为“不同物种总数”。在这个简单的例子中,由于只有 3 个物种(老虎、斑马、马)被用来生成这个摘要的 2 行,而不是“狮子”,所以“不同物种总数”应该是 3。但我想不通如何成功查询该号码。由于摘要查询必须使用 having 子句才能将过滤器应用于已分组和聚合的行集,因此这在尝试查询“不同物种总数”时会出现问题。
这会返回错误的数字 2,因为它不正确地是不同计数的不同计数:
SELECT
COUNT(DISTINCT distinct_species) AS distinct_species_total
FROM (
SELECT
age_range,
SUM(animals.weight) AS weight,
COUNT(DISTINCT animals.species) AS distinct_species
FROM animals
GROUP BY age_range
HAVING SUM(animals.weight) > 3
) x;
当然这会返回错误的数字 4,因为它没有考虑使用 having 子句过滤分组和聚合的摘要结果:
SELECT
COUNT(DISTINCT species) AS distinct_species_total
FROM animals;
感谢任何帮助我走上正确道路的帮助,并希望能帮助其他遇到类似问题的人,但最终我确实需要一个适用于 Amazon Redshift 的解决方案。
最佳答案
将结果集与原始动物表连接起来并计算不同的物种。
select distinct x.age_range,x.weight,count(distinct y.species) as distinct_species_total
from
(
select age_range,sum(animals.weight) as weight
from animals
group by age_range
having sum(animals.weight) > 3
) x
join animals y on x.age_range=y.age_range
关于postgresql - 查询用于创建分组、聚合和筛选行集的非重复计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50730495/