我想用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来实现呢?
发布于 2020-07-15 08:19:50
使用窗口函数。假设您的表具有列col1、col2、col3和col4,则为:
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发布于 2020-07-15 08:19:30
您可以使用窗口函数来计算累积和。我不明白你的例子中的总和是多少,但是语法是这样的:
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;https://stackoverflow.com/questions/62905773
复制相似问题