You can use a subquery in your HAVING clause to get this:
SELECT customerid,
sum(totaldue)
FROM SalesOrderHeader
GROUP BY customerid
HAVING sum(totaldue) = (
SELECT sum(totaldue)
FROM SalesOrderHeader
GROUP BY customerID
ORDER BY sum(totalDue) DESC LIMIT 1
)
The subquery:
SELECT sum(totaldue)
FROM SalesOrderHeader
GROUP BY customerID
ORDER BY sum(totalDue) DESC LIMIT 1
Is getting the largest customer's sum(totalDue)
by ordering the records by that sum(totaldue)
and then keeping only the first record LIMIT 1
. We use that in the HAVING
clause to compare that to the Sum(totaldue)
for each customer. If the customer in the main query has a sum(totaldue)
equivalent to the subquery's result, then we keep the record.
postgres=> CREATE TABLE salesorderheader
postgres-> (
postgres(> customerid integer,
postgres(> totaldue integer
postgres(> );
CREATE TABLE
postgres=> INSERT INTO salesorderheader VALUES
postgres-> (1, 10),
postgres-> (1, 12),
postgres-> (2, 22),
postgres-> (3, 5),
postgres-> (4, 4);
INSERT 0 5
postgres=> SELECT customerid, sum(totaldue) FROM SalesOrderHeader GROUP BY customerid HAVING sum(totaldue) = (SELECT sum(totaldue) FROM SalesOrderHeader GROUP BY customerID ORDER BY sum(totalDue) desc LIMIT 1);
customerid | sum
------------+-----
1 | 22
2 | 22
(2 rows)