I have a payments table that has a user_id and an amount. Users have a minimum withdrawal of $5.00, and they can have any number of payments to them. Their total balance isn’t stored anywhere (to keep it simple and avoid synchronization issues), instead it’s found by doing a query like:
SELECT SUM(amount)
FROM payment
WHERE user_id = 5;
I want to find out the grand total of all balances that meet the withdrawal requirement. What I wish I could do is something like:
SELECT SUM(SUM(amount))
FROM payment
WHERE sum(amount) >= 5.00
GROUP BY user_id;
Unfortunately I get the error
ERROR: aggregates not allowed in WHERE clause
How can I write this query? I’m using postgres 8.4.
Part 2:
I’m not sure if this is even possible, but this payments table also includes payments made by the user: the payment table includes amount, from_user_id, and to_user_id. It’s a single-entry accounting system. It would be great if I could also subtract the payments the user has made. The pseudo-sql is:
SELECT (sum of all amounts)
WHERE (sum(amount where to_user_id = 5) - sum(amount where from_user_id = 5)) > 5.00
You need to use the HAVING clause
Never heard anyone try and do nested aggregation. I suggest you do the inner bit separately, either with a
withstatment or using something likeI believe you want something like this for your second part, though I might be second-guessing.