postgresql 如何用postgres求条件内的运行和

wnavrhmk  于 2023-03-08  发布在  PostgreSQL
关注(0)|答案(2)|浏览(144)

我有下表

no status amount 
1  2      10000 
2  3      10000
3  2       1000
4  2     -11000

我用下面的查询运行了一些。

SELECT
    main.no
    , main.status
    , main.amount
    , SUM(main.amount) OVER ( 
        ORDER BY
            main.no ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
    ) 
from
    table AS main

它返回如下。但我想通过参考status代码来改进我的公式。

no status amount running_sum
1  2      10000  10000
2  3      10000  20000
3  2       1000  21000
4  2     -11000  10000

我想要的结果如下。
我想在另一个状态代码后,仅在status = 2中运行sum。

no status amount running_sum
1  2      10000  10000
2  3      10000  20000
3  2       1000  11000
4  2     -11000  0

如何在配方奶粉中添加调理剂?
有什么好办法可以做到这一点呢?
谢谢

wfveoks0

wfveoks01#

您可以使用sum(amount) over(partition by status order by no)执行此操作

SELECT
    main.no
    , main.status
    , main.amount
    , SUM(main.amount) OVER ( 
        partition by status
        ORDER BY
            main.no ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
    ) as running_sum
from
    mytable AS main
order by no

Demo here

csbfibhn

csbfibhn2#

根据您的预期输出,当status = 2时,您只需从运行和中减去status <> 2的运行和,尝试以下操作:

select main.no,
       main.status,
       main.amount,
       sum(main.amount) over (order by main.no) - 
       case when main.status = 2 
         then sum(case when main.status <> 2 then main.amount else 0 end) over (order by main.no) 
         else 0 
       end as running_sum
from table_name as main

Demo

相关问题