【问题标题】:Using CTE to calculate cumulative sum使用 CTE 计算累积和
【发布时间】:2020-11-04 09:57:30
【问题描述】:

我想在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 是如何完成的呢?

【问题讨论】:

  • 你的操作在我看来不像是累积的。例如,“6”是从哪里来的?

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


【解决方案1】:

使用窗口函数。假设您的表有列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

【讨论】:

    【解决方案2】:

    您将使用窗口函数来计算累积和。我看不到您的示例中的总和是多少,但语法类似于:

    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;
    

    【讨论】:

      猜你喜欢
      • 2016-05-11
      • 2019-07-08
      • 1970-01-01
      • 2020-12-17
      • 1970-01-01
      • 1970-01-01
      • 2023-01-18
      • 1970-01-01
      • 2019-06-06
      相关资源
      最近更新 更多