使用“lag()”窗口函数的PostgreSQL更新查询

问题描述 投票:2回答:1

我有一个涉及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)

这个会产生错误

用作表达式的子查询返回的多条记录

知道怎么做这个计算吗?

先感谢您。

sql postgresql
1个回答
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)上的索引。

© www.soinside.com 2019 - 2024. All rights reserved.