SQL Postgres使用avg列作为外部查询中的变量

时间:2014-08-02 15:47:38

标签: sql postgresql average

我写了以下查询:

SELECT DISTINCT gno, avg(weight) as x
    FROM Edge
    GROUP BY gno
    HAVING avg(weight)<max(weight)/2

并得到这个(正确的)表格: enter image description here

现在我想使用右列并在那里找到最大值并仅显示该行。 我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

如果我理解正确,请使用order bylimit

SELECT gno, avg(weight) as x
FROM Edge
GROUP BY gno
HAVING avg(weight)<max(weight)/2
ORDER BY avg(weight) desc
LIMIT 1;

请注意,使用group by时,您不需要select distinct

答案 1 :(得分:1)

您始终可以使用CTEs撰写此类查询:

WITH averages AS (
  SELECT DISTINCT gno, avg(weight) as x
    FROM Edge
    GROUP BY gno
    HAVING avg(weight)<max(weight)/2
)
SELECT MAX(x) FROM averages;

(但请注意CTEs are optimization fences