在Oracle SQL中运行Total - 插入缺少的行

时间:2016-10-04 13:14:58

标签: sql oracle

假设我在Oracle SQL数据库中有以下数据集:

Product  Year  Month  Revenue    
A        2016  1      7
A        2016  5      15

使用以下代码创建运行总计

select Product, Year, Month, Revenue,
       sum(Revenue) over (partition by Product, Year order by Month) Revenue_Running
  from exemplary_table

我收到以下结果:

Product  Year  Month  Revenue  Revenue_Running
A        2016  1      7        7
A        2016  5      15       22

有什么办法可以解决这个问题:

Product  Year  Month  Revenue  Revenue_Running
A        2016  1      7        7
A        2016  2      (null)   7
A        2016  2      (null)   7
A        2016  4      (null)   7
A        2016  5      15       22

1 个答案:

答案 0 :(得分:1)

您的calendar

需要Left join表和exemplary_table
SELECT p.product, 
       c.year, 
       c.month, 
       COALESCE(revenue, 0), 
       Sum(revenue)OVER (partition BY p.product, c.year  ORDER BY c.month) Revenue_Running 
FROM   calendar_table c 
       CROSS JOIN (SELECT DISTINCT product 
                   FROM   exemplary_table) p 
       LEFT JOIN exemplary_table e 
              ON c.year = e.year 
                 AND e.month = c.month 
WHERE  c.dates >= --your start date
       AND c.dates <= --your end date