One solution is to use the HAVING
clause with a correlated subquery that gets the max
value between all the sums
and restrict the rows to those whose SUM(amount_to_pay)
equals the max_value
.
SELECT
user_id,
SUM(amount_to_pay) AS total
FROM
reservation AS r
GROUP BY
user_id
HAVING
total = (SELECT SUM(amount_to_pay) AS tot
FROM reservation
GROUP BY user_id
ORDER BY tot DESC LIMIT 1)
Online example: DB-Fiddle
UPDATE POST COMMENTARY:
For sum
only the active
reservations you could take one of the next approaches:
A) Add the restriction on outer query and subquery:
SELECT
user_id,
SUM(amount_to_pay) AS total
FROM
reservation AS r
WHERE
status = "active"
GROUP BY
user_id
HAVING
total = (SELECT SUM(amount_to_pay) AS tot
FROM reservation
WHERE status = "active"
GROUP BY user_id
ORDER BY tot DESC LIMIT 1)
B) Use CASE WHEN ... END
inside the SUM()
method:
SELECT
user_id,
SUM(CASE WHEN status = "active" THEN amount_to_pay END) AS total
FROM
reservation AS r
GROUP BY
user_id
HAVING
total = (SELECT SUM(CASE WHEN status = "active" THEN amount_to_pay END) AS tot
FROM reservation
GROUP BY user_id
ORDER BY tot DESC LIMIT 1)
Online example: DB-Fiddle