Oracle sql查询:将方程式实现到选择组中

时间:2017-08-18 19:32:22

标签: sql oracle

我有以下加权平均方程式我试图将其放入select子句

((operating_hrsA *组件countA)+(operating_hrsC *组件countB)+(operating_hrsC *组件countC))/ total compont_countABC

我试图把它放入的选择是:

 SELECT reporting_date_from,
            reporting_date_to,
            b_name,
            oflag,
            component_type,
            SUM (component_count) AS component_count,
            --AVG (average_operating_hours) AS average_operating_hours,
            sum((average_operating_hours * component_count) / sum(component_count))  AS average_operating_hours


       FROM DEVICE
       where reporting_date_From = '01-JAN-2017' and b_name like '430%' 
   GROUP BY reporting_date_from,
            reporting_date_to,
            b_name,
            oflag,
            component_type;

我得到的错误是:

  

第1行的错误ORA-00937:不是单组组功能

表架构: 专栏|数据类型|空值 ? reporting_date_From date N. reporting_date_to日期N. b_name varchar2(100字节)Y oflag varchar2(50字节)Y component_type varchar2(50字节)Y average_operating_hours数字Y

数据样本 data sample 我对这个计算错误的想法是什么? 提前谢谢

2 个答案:

答案 0 :(得分:0)

您可以使用子选择来获取结果,然后执行意味着嵌套求和的计算,例如:

select  reporting_date_from,
            reporting_date_to,
            b_name,
            oflag,
            component_type,
            component_count, 
            average_operating_hours, 
            my_value/component_count as average_operating_hours
  from(           
      SELECT reporting_date_from,
              reporting_date_to,
              b_name,
              oflag,
              component_type,
              SUM (component_count) AS component_count,
              AVG (average_operating_hours) AS average_operating_hours,
              sum((average_operating_hours * component_count) )  AS my_value,

         FROM DEVICE
         where reporting_date_From = '01-JAN-2017' and b_name like '430%' 
     GROUP BY reporting_date_from,
              reporting_date_to,
              b_name,
              oflag,
              component_type

    )  t
    ;

答案 1 :(得分:0)

您可以使用窗口功能执行此操作。根据表格结构和所需结果,根据需要更改partition by列。

SELECT DISTINCT
reporting_date_from,
reporting_date_to,
b_name,
oflag,
component_type,
sum(component_count) over(partition by reporting_date_from,reporting_date_to,b_name,oflag) AS component_count,
sum(average_operating_hours * component_count) over(partition by reporting_date_from,reporting_date_to,b_name,oflag)
/ sum(component_count) over()  AS average_operating_hours,
FROM DEVICE
where reporting_date_From = '01-JAN-2017' and b_name like '430%'