从行中减去一个数字,直到数字结束为零

mec1mxoz  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(377)

在mysql中,如何使用queryupdate从行中减去一个数字,直到减法结束
如果有这样的table

Store Table
itemId  storeCode   qoh
1          1        20
1          2        30
1          3        40

我想从qoh中减去“80”,得到输出

itemId  storeCode   qoh
1          1        0
1          2        0
1          3        10

我试过了,但没有工作

set @sum = 80;
Update store SET qoh =
(SELECT IF((@sum := @sum - qoh) > 0,0,qoh))
ORDER BY storeCode ASC;

怎样做适当的调整?

oxalkeyp

oxalkeyp1#

如果您运行的是mysql 8.0,那么可以使用窗口函数进行计算。
以下 select 查询将提供预期结果:

select
    s.*,
    case when sum(qoh) over(partition by itemid order by storecode) - qoh >= 80 
        then qoh
        else greatest(
            sum(qoh) over(partition by itemid order by storecode) - 80,
            0
        )
    end new_qoh
from store s

你可以把它变成一个 update :

update store s
inner join (
    select 
        s.*, 
        sum(qoh) over(partition by itemid order by storecode) sum_qoh
    from store s
) n 
    on  n.itemid = s.itemid 
    and n.storecode = s.storecode
    and n.sum_qoh - s.qoh < 80
set s.qoh = greatest(n.sum_qoh - 80, 0)

db小提琴演示:

itemId | storeCode | qoh
-----: | --------: | --:
     1 |         1 |   0
     1 |         2 |   0
     1 |         3 |  10
     1 |         4 |  50

我在您的数据末尾添加了一行额外内容,以证明查询会留下“following” qon 没碰过。

相关问题