带有日期的Oracle窗口函数

时间:2015-09-16 14:05:24

标签: sql oracle

样本数据如下:

date       value  
2015-09-09      1  
2015-09-08      2  
2015-09-07      3  
2015-09-04      4  
2015-09-03      5  

我需要计算每个日期和前两天的总和值,因此结果应显示为:

2015-09-09      6 --sum value of 2015-09-09, 2015-09-08, 2015-09-07  
2015-09-08      5 --sum value of 2015-09-08, 2015-09-07  
2015-09-07      3 --sum value of 2015-09-07  
2015-09-04      9 --sum value of 2015-09-04, 2015-09-03  
2015-09-03      5 --sum value of 2015-09-03  

如何在Oracle中使用窗口函数实现它?

2 个答案:

答案 0 :(得分:2)

由于您的数据稀疏,您应该使用RANGE子句:

SELECT OrderDay, 
SUM(quantity) OVER 
(ORDER BY OrderDay RANGE BETWEEN INTERVAL '2' DAY PRECEDING AND CURRENT ROW) AS totals,
Quantity
FROM Order 
使用默认窗口

甚至更短:

SELECT OrderDay, 
SUM(quantity) OVER 
(ORDER BY OrderDay RANGE INTERVAL '2' DAY PRECEDING) AS totals,
Quantity
FROM Order 

答案 1 :(得分:0)

假设您有一个订单表, OrderDay 作为日期字段,数量作为当天的订单数量。现在必须按天订购并使用analytic function仅将当前日期和前两天相加。

关键是使用RANGE BETWEEN子句,该子句在包含当前和前两天的窗口上运行。这是一个解决方案:

SELECT 
SUM(Quantity) OVER 
(ORDER BY OrderDay RANGE BETWEEN
            INTERVAL '2' DAY PRECEDING
            AND
            CURRENT ROW ) totals,
Quantity
FROM Order