移动平均值为2列

时间:2010-11-04 13:39:09

标签: sql oracle oracle10g

您好我有问题。我知道如何使用oracle分析函数计算过去3个月的移动平均值...但我的情况有点不同

月-----产品类型-----销售----------平均(有必要找到)

1 ---------甲--------------- 10

1 ---------乙--------------- 12

1 ---------ç--------------- 17

2 ---------甲--------------- 21

3 ---------ç--------------- 2

3 ---------乙--------------- 21

4 ---------乙--------------- 23

5

6

7

8

9

因此,我们每个月和每种产品类型都有销售...我需要计算过去3个月的移动平均值和特定产品。

示例:

对于第4个月和产品B,它将是(21 + 0 + 12)/ 3

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

SELECT month, 
       productType, 
       sales,
       (lag(sales, 3) over (partition by produtType order by month) +
        lag(sales, 2) over (partition by productType order by month) + 
        lag(sales, 1) over (partition by productType order by month)/3 moving_avg
  FROM your_table_name

答案 1 :(得分:3)

另一个选择是使用分析函数的窗口子句

with my_data as (
  select 1 as month, 'A' as product, 10 as sales from dual union all
  select 1 as month, 'B' as product, 12 as sales from dual union all
  select 1 as month, 'C' as product, 17 as sales from dual union all
  select 2 as month, 'A' as product, 21 as sales from dual union all
  select 3 as month, 'C' as product, 2 as sales from dual union all
  select 3 as month, 'B' as product, 21 as sales from dual union all
  select 4 as month, 'B' as product, 23 as sales from dual 
)
select 
  month, 
  product, 
  sales,
  nvl(sum(sales) 
    over (partition by product order by month 
          range between 3 preceding and 1 preceding),0)/3 as average_sales
from my_data
order by month, product