使用CTE计算累计金额

时间:2020-07-15 00:18:22

标签: sql postgresql sum sql-order-by window-functions

我想在postgres中编写一个非递归公用表表达式(CTE)以计算累积和,这是输入表的示例:

----------------------
 1  |  A  |  0  | -1
 1  |  B  |  3  |  1
 2  |  A  |  1  |  0
 2  |  B  |  3  |  2

输出应如下所示:

----------------------
 1  |  A  |  0  | -1
 1  |  B  |  3  |  1
 2  |  A  |  1  | -1
 2  |  B  |  6  |  3

如您所见,第3列和第4列的累加总和已计算出来,使用递归CTE可以轻松做到这一点,但是使用非递归CTE怎么办?

2 个答案:

答案 0 :(得分:2)

使用窗口功能。假设您的表包含列col1col2col3col4,则应为:

select
    t.*,
    sum(col3) over(partition by col2 order by col1) col3,
    sum(col4) over(partition by col2 order by col1) col4
from mytable t

答案 1 :(得分:1)

您将使用窗口函数求和。我看不到您的示例中的总和,但是语法类似于:

select t.*, sum(x) over (order by y) as cumulative_sum
from t;

在您的示例中,这似乎是:

select t.*,
       sum(col3) over (partition by col2 order by col1) as new_col3,
       sum(col4) over (partition by col2 order by col1) as new_col4
from t;