oracle 2列移动平均数

p8h8hvxi  于 2023-11-17  发布在  Oracle
关注(0)|答案(2)|浏览(135)

你好,我有一个问题。我知道如何计算移动平均线过去3个月使用甲骨文分析函数......但我的情况有点不同
月-----产品类型------销售额---------平均值(必须找到此)
1-A-10
1-B-
1-C--17
2-A-21
3- 2
3-B-
4-B--23
5
6
7
8
9
所以我们每个月和每个产品类型的销售额.我需要计算过去3个月和特定产品的移动平均值。
举例说明:
对于第4个月和产品B,它将是(21+0+12)/3
有什么想法吗?

h43kikqp

h43kikqp1#

另一种选择是使用解析函数的窗口子句

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

字符串

5m1hhzi4

5m1hhzi42#

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

字符串
--已编辑以添加缺少的右括号

相关问题