【问题标题】:PostgreSQL query - AVG() function outside of temporary tablePostgreSQL 查询 - 临时表之外的 AVG() 函数
【发布时间】:2015-11-17 08:32:26
【问题描述】:

我目前有如下代码:

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

目前查询会拉出错误:ERROR: relationship "table_name" does not exist.

为什么会这样?

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

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

它会返回一个符合我预期的表,其中包含一个名为“num”的列。

附带说明一下,当我给表命名时(在本例中为 table_name),它在 SQL 中叫什么?我在标题中称之为临时表?在不知道它叫什么的情况下,很难找到解决这个问题的方法。

谢谢, 卡梅伦

【问题讨论】:

  • 有趣。我本来希望table_name 可以在这里找到。

标签: sql postgresql aggregate-functions average


【解决方案1】:

解决问题的一种方法是使用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;

【讨论】:

  • 非常感谢!这确实工作得很好,有一个小错误,即第三行开头的逗号不应该存在。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2022-11-22
    • 1970-01-01
    • 2013-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-23
    • 1970-01-01
    相关资源
    最近更新 更多