use mysql SUM() in a WHERE clause

前端 未结 4 1106
忘了有多久
忘了有多久 2020-12-01 11:32

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 pre

4条回答
  •  借酒劲吻你
    2020-12-01 12:21

    Not tested, but I think this will be close?

    SELECT m1.id
    FROM mytable m1
    INNER JOIN mytable m2 ON m1.id < m2.id
    GROUP BY m1.id
    HAVING SUM(m1.cash) > 500
    ORDER BY m1.id
    LIMIT 1,2
    

    The idea is to SUM up all the previous rows, get only the ones where the sum of the previous rows is > 500, then skip one and return the next one.

提交回复
热议问题