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

时间:2015-08-24 01:54:42

标签: sql postgresql aggregate-functions average

我目前有这些代码:

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

目前查询将引发错误:错误:关系“table_name”不存在。

为什么会这样?

正如我在代码中所说,我可以从the bracers中复制select语句:

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

它将返回一个我所期望的表,它包含一个名为'num'的列。

作为旁注,当我给表一个名称(在这种情况下为table_name)时,在SQL中调用了什么?我在标题中称它为临时表?如果不知道它的名称,就很难找到这个问题的解决方案。

谢谢, 卡梅伦

2 个答案:

答案 0 :(得分:1)

解决问题的一个解决方案是使用cte s。

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;

答案 1 :(得分:0)

另一种解决方案是使用窗口函数:

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