我有一个涉及Postgresql数据库的任务。我对SQL不太有经验。
我有一张桌子,上面有每周贸易产品的营业额。
对于每周,提供以下信息:产品,周数,每周营业额(可能是正数,也可能是负数,具体取决于天气是购买还是出售了更多产品)。我已经添加了一个列,每个星期都有期末余额。我在表中的第一周所有产品的期末余额(week_number= 0),而其他所有周均为“ null”。下面提供了一些示例性记录。
product | week_number | turnover | closing_balace --------------------------------+-------------+----------+---------------- BLGWK-05.00*1250*KR-S235JRN0-A | 0 | 50.00 | 1240.00 BLGWK-05.00*1250*KR-S355J2CN-K | 0 | 45.70 | 455.75 BLGWK-05.00*1464*KR-DD11NIET-K | 0 | 30.01 | 300.00 BLGWK-05.00*1500*KR-DD11NIET-R | 1 | 10.22 | BLGWK-05.00*1500*KR-S235J2CU-K | 1 | 88.00 |
我需要一个查询,以使用以下计算来填充所有“空”的“ closeing_balance”:
closing_balance = closing_balance of the same product for previous week + turnover for the week.
我试过这个查询:
update table_turnover set closing_balance = (select lag(closing_balance, 1) over (partition by product order by week_number) + turnover) where week_number > 0;
它从未成功过-高于“第0周”的“ closed_balance”的“空”值仍然为“空”。
我也尝试过:
update table_turnover set closing_balance = (select case when week_number = 0 then closing_balance else (lag(closing_balance, 1) over (partition by product order by week_number) + turnover) end from table_turnover)
这产生一个错误
子查询返回的多个记录用作表达式
知道如何进行此计算吗?
先感谢您。
在from子句中使用子查询:
from
update table_turnover set closing_balance = (ttprev.prev_closing_balance + ttprev.turnover) from (select tt.*, lag(closing_balance) over (partition by product order by week_number) as prev_closing_balance from table_turnover tt ) ttprev where ttprev.product = tt.product and ttprev.week_number = tt.week_number and week_number > 0;
或者,如果您想在中使用子查询select:
select
update table_turnover set closing_balance = (turnover + (select tt2.closing_balance from table_turnover tt2 where tt2.product = tt.product and tt2.week_number = tt.week_number - 1 ) ) where week_number > 0;
为了提高性能(在任何一个版本上),您都希望在上建立索引table_turnover(product, week_number, closing_balance)。
table_turnover(product, week_number, closing_balance)