如何解决如何使用光标更新组行逐行
商店 | 产品 | 开始数量 | 收货数量 | 销售数量 | EndQty | 日期 |
---|---|---|---|---|---|---|
1 | A | 100 | 0 | 30 | 80 | 2020-10-21 |
1 | A | -- | 100 | 30 | -- | 2020-10-23 |
2 | B | 150 | 150 | 50 | 250 | 2020-10-21 |
2 | B | -- | 0 | 20 | -- | 2020-10-22 |
2 | B | -- | 0 | 30 | -- | 2020-10-24 |
如何更新下一行 (--)? 结果
商店 | 产品 | 开始数量 | 收货数量 | 销售数量 | EndQty | 日期 |
---|---|---|---|---|---|---|
1 | A | 100 | 0 | 30 | 80 | 2020-10-21 |
1 | A | 80 | 100 | 30 | 150 | 2020-10-23 |
2 | B | 150 | 150 | 50 | 250 | 2020-10-21 |
2 | B | 250 | 0 | 50 | 200 | 2020-10-22 |
2 | B | 200 | 0 | 40 | 160 | 2020-10-24 |
BeginQty + ReceiptQty - SaleQty = EndQty 日期2020-10-21有完整数据
解决方法
您可以使用如下解析函数:
select Store,Product,sum(BeginQty + ReceiptQty - SaleQty) over (partition by store,product order by date) - ReceiptQty + SaleQty as BeginQty,ReceiptQty,SaleQty,product order by date) as EndQty,Date
from your_Table
,
您不会为此使用游标。事实上,一般规则是尽可能避免使用游标。如果您认为有问题需要使用游标,请退回。好的,有时它们很有用。 . .规范情况是您需要在每一行上调用存储过程。差不多就是这样。
您的案例对日期有非常具体的规定。我注意到第一个 endqty
与您指定的算术不匹配。所以:
with toupdate as (
select t.*,max(case when date = '2020-10-21' then endqty end) over (partition by store,product) as first_endqty,sum(case when date <> '2020-10-21' then ReceiptQty - SaleQty else 0 end) over (partition by store,product order by date) as inc
from t
)
update toupdate
set endqty = first_endqty + inc,beginqty = first_endqty + inc - (ReceiptQty - SaleQty)
where date <> '2020-10-21';
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。