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

Calculating Running Totals, keeping constant for each month

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

我试过这个:

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 |
+------------+-----+

我该如何解决这个问题?提前致谢!

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

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