SQL 缺少分组值时不显示累积总和

SQL Cumulative Sum not showing when group by values are missing

我有一些月度数据如下:

Month     | Category          | Monthly Value
2020-07-01| Food              | 1
2020-07-01| Entertainment     | 4
2020-08-01| Entertainment     | 2
2020-09-01| Entertainment     | 1

我想计算每个类别的累计总和,得到如下结果:

Month       |  Category     | Cumulative Sum
2020-07-01  |  Food         |   1
2020-08-01  |  Food         |   1
2020-09-01  |  Food         |   1
2020-07-01  | Entertainment |   4
2020-08-01  | Entertainment |   6
2020-09-01  | Entertainment |   7

我正在编写 window 求和查询,如下所示:

    SELECT
      month
    , category
    , sum("monthly value") OVER (PARTITION BY "category" ORDER BY "month" ASC ROWS UNBOUNDED PRECEDING) AS "Cumulative Sum"
    from (
select date_trunc('month', daily_date) as month, category, sum(daily_value) as "monthly value"
from sample_table 
group by date_trunc('month', daily_date) as month, category)

但是,我得到如下信息:

Month           |  Category     | Cumulative Sum
    2020-07-01  |  Food         |   1
    2020-07-01  | Entertainment |   4
    2020-08-01  | Entertainment |   6
    2020-09-01  | Entertainment |   7

为什么 2020-08-012020-09-01 月份的“食品”类别的累计金额未显示?我怎样才能使结果按预期显示(显示在第二个table)。

顺便说一句,我正在使用 Redshift。 谢谢!

使用 cross join 生成行,然后 left join 引入值:

select m.month, c.category, t.monthly_value,
       sum(t.monthly_value) over (partition by c.category order by m.month) as running_monthly_value
from (select distinct month from t) m cross join
     (select distinct category from t) c left join
     t
     on t.month = m.month and t.category = c.category;