2017-10-19 57 views
2

我有一個要求,可以根據YEAR(需要編寫Oracle查詢)按數量總和查找最大值。Oracle查詢累計數量(僅限於最近3年)

對於實例

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 (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。我只需要考慮最近3年捲起的AVG並分配最大值

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

那是所希望的輸出? 2016年ID 101如何在新欄目中分配值13?如果這不是所需的輸出,請編輯以顯示(正確)所需的輸出。尤其是,對於ID 101(例如),2014年和2015年應該展示什麼,當時還沒有三年需要考慮?也許在2014年只顯示數量(10),2015年顯示最大11/1和(10 + 11)/ 2?如果沒有,還有什麼? – mathguy

+1

另請參見:您的Oracle版本是由'select * from v $ version'報告的? – mathguy

+0

@mathguy - 版本是Oracle Database 12c企業版版本12.1.0.2.0 - 64位生產 – beckham

回答

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 
; 
+0

這工作。我已經改變了查詢更加動態。:) 'select item_id,org_id,yr,qty, 最大( avg(case when yr =(從double中選擇to_char(sysdate,'YYYY'))然後qty結束)over(partition by item_id,org_id), avg(case when yr> =(從double中選擇to_char(sysdate,'YYYY') - 1)然後qty結束)over(partition by item_id,org_id), avg(case when you> =(select to_char(sysdate, 'YYYY') - 2 from dual)then qty end)over(partition by item_id,org_id) )as max_avg from inputs_table ;' – beckham

+0

@beckham - Cool - 您的想法完全正確。 – mathguy

2

一種方法是使用解析函數兩個級別:

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 
+0

這不是OP正在尋找的東西。在「分區」中,他僅查看2017年,2017年和2016年以及2017年,2016年和2015年的平均值。這是所有年份中的「最大值」,包括2011年和2012年以及2013年。沒有解釋非常清楚的在原帖中,但在評論中已經澄清了。 – mathguy

+0

@ Gordon - 我認爲這個查詢會起作用,但它仍然沒有工作,並且它的2014年計算結果也是如此 – beckham

+0

@ beckham ...窗口條款需要去另一個方向 - 2以下,而不是2前面。 –