PostgreSQL:子查询上的聚合表达式

时间:2018-08-01 01:36:20

标签: postgresql subquery aggregate-functions

一个初学者的总问题:我想使用GROUP BY语句运行子查询,然后在结果中找出具有最大值的行。我已经建立了如下表达式:

SELECT agg.facid, agg.Slots
FROM
(SELECT facid AS facid, SUM(slots) AS Slots FROM cd.bookings
GROUP BY facid
ORDER BY SUM(slots) DESC) AS agg
WHERE agg.Slots = (SELECT MAX(Slots) FROM agg);

在我看来,这应该首先创建一个带有facid和SUM(slots)值的2列表,然后将这些列分别命名为agg.facid和agg.Slots,我应该只在“插槽”。但是,相反,我收到此错误:

ERROR:  relation "agg" does not exist
LINE 6: WHERE agg.Slots = (SELECT MAX(Slots) FROM agg);

这可能很简单,所以对于一个愚蠢的问题,我先感到抱歉;)

我正在使用pgAdmin 4在PostgreSQL 10上工作。

3 个答案:

答案 0 :(得分:1)

使用Common Table Expression:

WITH agg AS (
    SELECT facid AS facid, SUM(slots) AS Slots 
    FROM cd.bookings
    GROUP BY facid
    )
SELECT agg.facid, agg.Slots
FROM agg
WHERE agg.Slots = (SELECT MAX(Slots) FROM agg);

答案 1 :(得分:0)

这是您想要的吗?

SELECT
    facid,
    SUM(slots)
FROM cd.bookings
GROUP BY
    facid
HAVING SUM(slots) = MAX(slots)

答案 2 :(得分:0)

因此,需要进行更多的研究,我发现了一个使用通用表表达式的解决方案,它可能足以满足我的喜好:

WITH sum AS (SELECT facid, SUM(slots) AS Slots FROM cd.bookings GROUP BY facid)
SELECT facid, Slots
FROM sum
WHERE Slots = (SELECT MAX(Slots) FROM sum);

第一行声明一个CTE,稍后可为子查询调用CTE,以计算聚合插槽列中的最大值是多少。 希望它可以帮助任何有兴趣的人。