将每行具有最近日期的表联接在一起,然后进行加权平均

时间:2019-01-03 16:06:59

标签: sql oracle join aggregation

Oracle DB中有三个表,例如equip_type,output_history和time_history。 是否有一种方法可以将下面的(1)所示的三个表连接起来,然后再按照下面的(2)的所示获得加权平均值?

--equip_type table and the date
CREATE TABLE equip_type  (  
  EQUIP_TYPE VARCHAR(60),    
  EQUIP VARCHAR(60)
  );
INSERT INTO equip_type  VALUES ('A','e1');

-- output_history and data
CREATE TABLE output_history (  
  EQUIP VARCHAR(60),     
  MODEL VARCHAR(60),     
  Data1 VARCHAR(60),        
  QUANTITY  NUMBER(10) 
  );
INSERT INTO output_history VALUES ('e1','m1','20180103',10);
INSERT INTO output_history VALUES ('e1','m1','20180106',20);


--time_history table and data
CREATE TABLE time_history (  
  EQUIP VARCHAR(60),     
  MODEL VARCHAR(60),       
  Data2 VARCHAR(60),    
  time NUMBER(10)
  );
INSERT INTO time_history VALUES ('e1','m1','20180101',6);
INSERT INTO time_history VALUES ('e1','m1','20180105',5);

(1)如何获得如下所示的联接表?

 EQUIP MODEL DATE1  QUANTITY   DATE2   TIME  TYPE
 ---- ---- ---------- ------  -------- ----  ----
  e1    m1  20180103  10      20180101   6    A
  e1    m1  20180106  20      20180105   5    A

对于OUTPUT_HISTORY中的每一行,* TIME_HISTORY中DATE1点的最新行将被合并。

(2)然后,使用上面的连接表,如何获取TIME的加权平均值?

(QUANTITY * TIME) / sum of QUANTITY group by TYPE, MODEL

 for example,(10×6 + 20×5)÷(10+20) for equip type A and model m1

1 个答案:

答案 0 :(得分:0)

一种方法使用分析函数来获取最新记录,然后进行简单汇总

select sum(quantity * time) / sum(quantity)
from output_history oh left join
     (select th.*,
             row_number() over (partition by equip, model order by date2 desc) as seqnum
      from time_history th
     ) th
     on oh.equip = th.equip and oh.model = th.model and th.seqnum = 1
group by equip, model;