gpt4 book ai didi

sql - 对动态行 postgresql 使用 lag()

转载 作者:行者123 更新时间:2023-11-29 12:25:08 25 4
gpt4 key购买 nike

我有一个名为“数量”的表,如下所示

表 1:

----------------------------------------------------
Price | A_Quantity | B_Quantity | Remaining_quantity
----------------------------------------------------
30 | 17 | 2 | 0
32 | 17 | 4 | 0
33 | 17 | 4 | 0
----------------------------------------------------

我希望字段 - Remaining_quantity 填写如下

表 2:

----------------------------------------------------
Price | A_Quantity | B_Quantity | Remaining_quantity
----------------------------------------------------
30 | 17 | 2 | 15
32 | 17 | 4 | 11
33 | 17 | 4 | 7
----------------------------------------------------

我使用了下面的查询,但没有给出预期的结果。

update quantity set remaining_quantity = remaining_quantity - 
(lag(B_Quantity) OVER (ORDER BY price))

最佳答案

这是一种方法。

注意:通过查看数据,看起来没有特定的主键,但是 pricea_quantity 的组合看起来是唯一的,因此我在 加入。如果这只是您的示例数据并且实际上您确实有一个主键,我建议您将连接条件更改为该主键

REXTESTER DEMO

update Table1
set remaining_quantity = upd_tbl.cum
from
(
select t.*
,a_quantity - sum(b_quantity) over (partition by a_quantity order by price) as cum
from table1 t
) upd_tbl
where table1.price=upd_tbl.price
and table1.a_quantity=upd_tbl.a_quantity;

解释:sum(b_quantity) over (partition by a_quantity order by price) 将为您提供分区 (2,6,10..) 的累积和。现在您可以从 a_quantity 中减去它以获得输出。

关于sql - 对动态行 postgresql 使用 lag(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44212003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com