Oracle Query to rollup QTY by Year- only last 3 years

喜你入骨 提交于 2019-12-22 16:52:29

问题


I have a requirement to find out MAX VALUE from SUM of Quantities Divided by YEAR (Need to write a Oracle Query).

For Example

 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

My Output should be like this :-

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 (11+12+13/3, 12+13/2, 13/1)... max(11.5, 12, 12.5, 13) = 13... I should not consider 10+11+12+13/4. I only need the consider the AVG rolled up by last 3 years and assign the Max Value

 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

Any help would be greatly appreciated.


回答1:


select item_id, org_id, yr, qty,
       greatest (
 avg(case when yr = 2017                then qty end) over (partition by item_id, org_id),
 avg(case when yr in (2016, 2017)       then qty end) over (partition by item_id, org_id),
 avg(case when yr in (2015, 2016, 2017) then qty end) over (partition by item_id, org_id)
       ) as max_avg
from   inputs_table
;



回答2:


One method uses two levels of analytic functions:

select t.*, max(running_avg_3) over (partition by item_id)
from (select t.*,
             avg(qty) over (partition by item_id order by year desc
                            rows between current row and 2 following
                           ) as running_avg_3
      from t
     ) t


来源:https://stackoverflow.com/questions/46833821/oracle-query-to-rollup-qty-by-year-only-last-3-years

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!