【发布时间】:2010-09-13 23:36:45
【问题描述】:
我需要在 Postgresql 8.3 中通过嵌套子查询获得的一堆不同聚合上执行相同的分组。
如果我这样做:
select f10 as report_id,
(SELECT AVG(age)
FROM (select f10 as report_id,
f62 as age
from reports
where f55 in ('1'))
and f62 in ('1', '2', '3', '4', '5'))) foo
group by report_id) as agg1,
(SELECT AVG(age)
FROM (select f10 as report_id,
f62 as age
from reports
where f55 in ('2'))
and f62 in ('1', '2', '3', '4', '5'))) foo
group by report_id) as agg2,
from reports
group by report_id;
这几乎是我想要的,但 group by 没有做任何事情 - 所有聚合都是相同的,它是所有 report_ids 的聚合。我希望每个 report_id 有一个单独的聚合。
如果我尝试在聚合中进行分组,那么我不能返回超过 2 个字段或行,因此它不起作用。
有人建议我这样做
sum(case
when f55 in ('1') then f62
else 0
end) / sum(case
when f55 in ('1') then 1
else 0
end)
...等等。对于每个聚合,但我认为这不是一个好方法。只是似乎想不出更好的办法。
【问题讨论】:
标签: sql postgresql aggregate-functions