3

A total beginner's question: I wanted to run a sub-query with GROUP BY statement, and then find out a row with maximum value in the result. I have built an expression like that below:

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);

In my mind, this should first create a 2-column table with facid and SUM(slots) values, and then by addressing these columns as agg.facid and agg.Slots I should get only the row with max value in "Slots". However, instead I am getting this error:

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

This is probably something very simple, so I am sorry in advance for a silly problem ;)

I am working on PostgreSQL 10, with pgAdmin 4.

2
  • Check out the HAVING clause, should be able to do it without a subquery even. Commented Aug 1, 2018 at 1:42
  • If I using HAVING statement like so, I still get an error:SELECT agg.facid, agg.Slots FROM (SELECT facid AS facid, SUM(slots) AS Slots FROM cd.bookings GROUP BY facid HAVING Slots = MAX(Slots)) AS agg; ERROR: column "bookings.slots" must appear in the GROUP BY clause or be used in an aggregate function Commented Aug 1, 2018 at 1:48

3 Answers 3

4

Use a 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);
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, noticed your answer after the web page refreshed upon posting an answer to my own question ;) Thanks for your feedback mate!
1

So a bit more of a research, and I figured a solution which might be clean enough to my liking, using a Common Table Expression:

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);

The first line declares a CTE, which can later be called for a sub-query calculating what is the max value in aggregated slots column. Hope it helps anyone interested.

Comments

0

Does this do what you are looking for?

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

1 Comment

Unfortunately, it does not work mate, because that MAX(slots) function just picks a max value in a single slots cell, before summing them up by facid.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.