我正在为一个项目开发sql,我需要根据一些规则更新soh\u wh\u a和soh\u whu\u b。
这是表a:
| Code | Warehouse | StockOnHand | Wh_A | Wh_B
----------------------------------------------------
| 001 | A | 10 | NULL | NULL
| 001 | B | 20 | NULL | NULL
| 003 | A | 30 | NULL | NULL
| 033 | B | 40 | NULL | NULL
我想填充wh\u a和wh\u b列。例如,让我们处理第一行,wh_a应该与stockonhand列的值相同,因为这一行属于仓库“a”。使用updatecase-when语句很容易做到这一点。
对我来说,困难的是用第二行的stockonhand列填充wh\u b列。
table的尽头应该是这样的。
| Code | Warehouse | StockOnHand | Wh_A | Wh_B
----------------------------------------------------
| 001 | A | 10 | 10 | 20
| 001 | B | 20 | 10 | 20
| 003 | A | 30 | 30 | 40
| 033 | B | 40 | 30 | 40
这就是我到目前为止所做的。。。
update Table_A set
Wh_A = (case
when warehouse = 'A' then stockOnHand
when warehouse = 'B' then ... end)
Wh_B = (case
when warehouse = 'A' then stockOnHand
when warehouse = 'B' then ... end)
2条答案
按热度按时间zqry0prt1#
可以使用窗口函数:
很容易把它变成一个
update
使用可更新的cte进行查询:kkbh8khc2#