PostgreSQL 查询 - 临时 table 之外的 AVG() 函数

PostgreSQL query - AVG() function outside of temporary table

我目前有这些代码:

SELECT num
  FROM (
        SELECT ... Code that returns the table I would expect ...
  ) table_name
WHERE num > (SELECT AVG(num) FROM table_name);

目前查询会报错:错误:关系"table_name"不存在。

为什么会这样?

正如我在代码中所说,我可以从括号内部复制 select 语句:

SELECT ... Code that returns the table I would expect ...

它会 return 一个 table 正如我所料,它包含一个名为 'num'.

的列

作为旁注,当我给 table 一个名字(在本例中为 table_name)时,它在 SQL 中叫什么?我在标题中称它为临时 table ?在不知道这个问题叫什么的情况下很难找到解决这个问题的方法。

谢谢, 卡梅伦

解决您的问题的一种方法是使用 ctes。

with table_name as
(SELECT ... Code that returns the table I would expect ...)
,avg_num as (select avg(num) as avgnum from table_name)
select t.num 
from table_name t join avg_num a
on t.num > a.avgnum;

另一个解决方案是使用window函数:

SELECT num
FROM (SELECT num, AVG(num) OVER () as avgnum
      FROM . . .    Code that returns the table I would expect ...
     ) table_name
WHERE num > avgnum;