sql - Oracle 查询按年份汇总数量 - 仅过去 3 年

标签 sql oracle oracle12c

我需要从数量总和除以年份中找出最大值(需要编写 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 (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

任何帮助将不胜感激。

最佳答案

一种方法使用两级分析函数:

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

关于sql - Oracle 查询按年份汇总数量 - 仅过去 3 年,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46833821/

相关文章:

sql - ORA-01652 : unable to extend temp segment by 128 in tablespace SYSTEM: How to extend?

sql - 向 PostgreSQL 数据库的所有模式中的表添加一列

sql - 解读 Oracle 查询计划中的 HASH JOIN

sql - 在触发器中使用 DBMS_PIPE.PACK_MESSAGE 和 DBMS_PIPE.SEND_MESSAGE

mysql - 多重连接过滤

c# - SQL 查询错误

oracle - 为什么 View 列的类型与相应的函数结果类型不匹配?

oracle - Oracle PL/SQL-立即输出/控制台打印的提示

sql - Maximo 中的 ASSET 表是否有主键?

oracle - Maximo:ASSET 表有重复索引?