【问题标题】:Subtract a number from the rows until the number ends to zero从行中减去一个数字,直到数字结束为零
【发布时间】:2020-06-28 21:31:05
【问题描述】:

如何通过查询更新从行中减去一个数字到 MySQL 中的减法末尾

如果有这样的表

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;

什么是适当的调整?

【问题讨论】:

    标签: mysql sql sum sql-update window-functions


    【解决方案1】:

    如果您运行的是 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)
    

    Demo on DB Fiddle

    项目 ID |商店代码 |呸 -----: | --------: | --: 1 | 1 | 0 1 | 2 | 0 1 | 3 | 10 1 | 4 | 50

    我在您的数据末尾添加了一个额外的行,以证明查询使“以下”qon 保持不变。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 2019-05-13
      相关资源
      最近更新 更多