Postgres - 在子查询中使用别名列

问题描述

是否可以从外部查询获取别名列并使用它来过滤子查询。本质上,我想做这样的事情

select distinct 
    array_agg(foo.id) as foo_list,(select sum(data) from foo where id in foo_list)
from foo
where x

但是“foo_list”处或附近的语法错误

解决方法

试试这个:

with temp as
(
  select distinct array_agg(foo.id) as foo_list from foo
)
select sum(data) from foo 
where id in (select  foo_list from temp)