Select rows until a total amount is met in a column (mysql)

前端 未结 5 847
再見小時候
再見小時候 2020-12-19 23:41

I have seen this issue in SF, but me being a noob I just can\'t get my fried brain around them. So please forgive me if this feels like repetition.

My Sample Table

5条回答
  •  眼角桃花
    2020-12-19 23:49

    How about this? Using two variables.

    SQLFIDDLE DEMO

    Query:

    set @tot:=0;
    set @sup:=0;
    
    select x.id, x.supplier, x.ctot
    from (
    select id, supplier, qty,
    @tot:= (case when @sup = supplier then
    @tot + qty else qty end) as ctot,
    @sup:=supplier
    from demo
    order by supplier asc, id desc) x
    where x.ctot >=5
    ;
    
    | ID | SUPPLIER | CTOT |
    ------------------------
    |  2 |        1 |    5 |
    |  1 |        1 |    7 |
    |  3 |        2 |    5 |
    

提交回复
热议问题