我要求从YEAR划分的数量的和中找出最大值(需要编写Oracle查询)。
例如
ITEM_ID ORG_ID YEAR QTY
100 121 2015 10
100 121 2016 5
100 121 2017 8
101 146 2014 10
101 146 2015 11
101 146 2016 12
101 146 2017 13
我的输出应该是这样的: -
for Item_id 100,121 the max_avg should be max(10+5+8/3, 5+10/2, 10/1)... max (7.6, 7.5, 8) = 8
for Item_id 101,146 the max_avg should be max(10+11+12+13/4, 11+12+13/3, 12+13/2, 13/1)... max(11.5, 12, 12.5, 13) = 13
ITEM_ID ORG_ID YEAR QTY MAX_AVG
100 121 2015 10 8
100 121 2016 5 8
100 121 2017 8 8
101 146 2014 10 13
101 146 2015 11 13
101 146 2016 12 13
101 146 2017 13 13
非常感谢任何帮助。
答案 0 :(得分:2)
您需要两层分析函数:您需要分析MAX(某些)因为您想要返回原始表中的所有行;在MAX内你需要分析(滚动)平均值。分析函数不能嵌套,因此您需要子查询和外部查询。像这样:
with inputs ( item_id, org_id, yr, qty ) as (
select 100, 121, 2015, 10 from dual
union all select 100, 121, 2016, 5 from dual
union all select 100, 121, 2017, 8 from dual
union all select 101, 146, 2014, 10 from dual
union all select 101, 146, 2015, 11 from dual
union all select 101, 146, 2016, 12 from dual
union all select 101, 146, 2017, 13 from dual
)
-- End of simulated inputs (for testing only, not part of the solution).
-- SQL query begins BELOW THIS LINE. Use your actual table and column names.
select item_id, org_id, yr, qty,
max(forward_avg) over ( partition by item_id, org_id ) as max_avg
from ( select item_id, org_id, yr, qty,
avg(qty) over ( partition by item_id, org_id
order by yr desc ) as forward_avg
from inputs i
) b
order by item_id, org_id, yr -- If needed
;
ITEM_ID ORG_ID YR QTY MAX_AVG
---------- ---------- ---------- ---------- ----------
100 121 2015 10 8
100 121 2016 5 8
100 121 2017 8 8
101 146 2014 10 13
101 146 2015 11 13
101 146 2016 12 13
101 146 2017 13 13