【问题标题】:Calculating Running Totals, keeping constant for each month计算运行总计,每个月保持不变
【发布时间】:2019-06-02 15:19:03
【问题描述】:

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

我试过了:

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

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

【问题讨论】:

    标签: sql postgresql window-functions cumulative-sum


    【解决方案1】:

    首先获取不同 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

    【讨论】:

      猜你喜欢
      • 2016-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-24
      • 1970-01-01
      • 2020-05-13
      • 1970-01-01
      相关资源
      最近更新 更多