2016-10-04 50 views
2

假设我已经在甲骨文的SQL数据库以下组数据:用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

你需要一个calendar表和Left joinexemplary_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