简体   繁体   English

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

[英]Calculating Running Totals, keeping constant for each month

I need to calculate the running total, would like a constant number for each month, only to have it increase by a specific amount for each succeeding month. 我需要计算运行总计,希望每个月都有一个恒定的数字,只是要让每个接下来的月份增加一定的数量。 However I can't group or partition out the dates to do this... and I only know about the code to write a continuous running total. 但是,我无法将日期分组或分割以执行此操作...,而且我只知道编写连续运行总计的代码。

I've tried this: 我已经试过了:

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

..which is wrong because I want this: ..这是错误的,因为我想要这样:

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

How do I approach this problem? 我该如何解决这个问题? Thanks in advance! 提前致谢!

First get the running sum over the distinct monthdates and then join them to your table on the monthdates . 首先获取不同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;

You could solve it even easier by using dense_rank() multiplied by 10 , but without sum() . 您可以通过使用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 分贝<>小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM