代码之家  ›  专栏  ›  技术社区  ›  Thomas Price

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

  •  0
  • Thomas Price  · 技术社区  · 7 年前

    我需要计算运行总数,希望每个月都有一个常数,只是在接下来的每个月增加一个特定的数量。但是我不能将日期分组或划分出来…我只知道写连续运行总数的代码。

    我试过了:

    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 回复  |  直到 7 年前
        1
  •  0
  •   sticky bit    7 年前

    首先,在distinct上获取运行和 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