我有一个涉及Postgresql数据库的任务。我对SQL不是很熟悉。
我有一张每周交易产品营业额的表格。
每周提供以下信息:产品,周数,每周营业额(可能是正数或负数,具体取决于购买或销售产品的天气情况)。我已经为每周添加了一个具有期末余额的列。我在表格中为第一周的所有产品(week_number = 0)设置了期末余额,但是对于所有其他周期我都是“空”。下面提供了一些示例性记录。
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 |
我需要一个查询来填充所有“null”closing_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周”以上的closing_balance的“null”值仍为“null”。
我也尝试过:
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)
这个产生错误
用作表达式
的子查询返回的多条记录
知道怎么做这个计算吗?
提前谢谢。
答案 0 :(得分:1)
在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
中使用子查询:
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)
上的索引。