一个初学者的问题:我想用分组语句运行子查询,然后在结果中找出一个值最大的行。我建立了这样一个表达式:
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)值的两列表,然后通过将这些列寻址为agg.facid和agg.slots,我应该只得到“slots”中最大值的行。然而,我得到的却是这个错误:
ERROR: relation "agg" does not exist
LINE 6: WHERE agg.Slots = (SELECT MAX(Slots) FROM agg);
这可能是很简单的事情,所以我为一个愚蠢的问题提前道歉;)
我在用pgAdmin 4开发PostgreSQL 10。
最佳答案
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);
关于postgresql - PostgreSQL:子查询上的聚合表达式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51624199/