suppose I have this table
id | cash
1 200
2 301
3 101
4 700
and I want to return the first row in which the sum of all the previous cash is greater than a certain value:
So for instance, if I want to return the first row in which the sum of all the previous cash is greater than 500, is should return to row 3
How do I do this using mysql statement?
using WHERE SUM(cash) > 500
doesn’t work
You can only use aggregates for comparison in the HAVING clause:
The
HAVINGclause requires you to define a GROUP BY clause.To get the first row where the sum of all the previous cash is greater than a certain value, use:
Because the aggregate function occurs in a subquery, the column alias for it can be referenced in the WHERE clause.