计算运行总计,每个月保持不变

时间:2019-01-07 23:17:41

标签: sql postgresql window-functions cumulative-sum

我需要计算运行总额,希望每个月都有一个恒定的数字,只是要让其随后的每个月增加特定的数量。但是,我无法对日期进行分组或划分来执行此操作……而且我只知道编写连续运行总计的代码。

我已经尝试过了:

SELECT 
    monthdates,
    sum(10) OVER (
        PARTITION BY monthdates ORDER BY monthdates ASC rows between unbounded preceding and current row)
FROM mytable;

..这是错误的,因为我想要这个:

+------------+-----+
| monthdates | sum |
+------------+-----+
| 2018-01-01 |  10 |
| 2018-01-01 |  10 |
| 2018-02-01 |  20 |
| 2018-02-01 |  20 |
| 2018-02-01 |  20 |
| 2018-02-01 |  20 |
| 2018-02-01 |  20 |
| 2018-03-01 |  30 |
| 2018-03-01 |  30 |
+------------+-----+

如何解决此问题?预先感谢!

1 个答案:

答案 0 :(得分:0)

首先获取不同monthdates上的运行总和,然后将它们加入到monthdates上的表中。

SELECT t2.monthdates,
       x2.sum
       FROM mytable t2
            INNER JOIN (SELECT x1.monthdates,
                               sum(10) OVER (ORDER BY x1.monthdates) sum
                               FROM (SELECT DISTINCT
                                            t1.monthdates
                                            FROM mytable t1) x1) x2
                       ON x2.monthdates = t2.monthdates
       ORDER BY t2.monthdates;

使用dense_rank()乘以10,但不使用sum(),则可以更轻松地解决它。

SELECT t1.monthdates,
       dense_rank() OVER (ORDER BY t1.monthdates) * 10 sum
       FROM mytable t1
       ORDER BY t1.monthdates;

db<>fiddle

相关问题