从平均Oracle SQL中减去

时间:2019-05-25 07:56:05

标签: oracle oracle-sqldeveloper

我想从一个表中计算出一列的平均值,然后从另一张表中的平均值中减去实际值。

该过程将实际收取的价格减去平均价格。

我收到一个错误:“单行子查询返回多个行”

我的查询:

select proc_std_cost,adprc_pat_cost, 
(select round(avg(adprc_pat_cost),2) from adm_prc group by proc_code) as avgerage,
proc_std_cost-(select round(avg(adprc_pat_cost),0) from adm_prc group by proc_code) as difference
from procedure p join adm_prc a on (a.proc_code=p.proc_code);

如果我更改查询并删除该组,则会得到不需要的结果。因为它显示的是总平均值而不是分组平均值。

enter image description here

表样本:

adm_prc

enter image description here

程序

enter image description here

谢谢

1 个答案:

答案 0 :(得分:0)

我想AVG函数的解析形式可能会有所帮助。这是一个例子。我不想键入那么多的值(因为您没有提供CREATE TABLE和INSERT INTO示例数据),但是我希望您能理解所有内容。注意第20和21行。

SQL> with adm_prc (proc_code, adprc_pat_cost) as
  2    (select 12055, 250    from dual union all
  3     select 43111, 355    from dual union all
  4     select 15510, 75     from dual union all
  5     select 19887, 68     from dual union all
  6     select 29844, 109.28 from dual union all
  7     select 33335, 70.45  from dual
  8    ),
  9  procedure (proc_code, proc_std_cost) as
 10    (select 12055, 250    from dual union all
 11     select 15509, 75     from dual union all
 12     select 15510, 75     from dual union all
 13     select 15511, 200    from dual union all
 14     select 17122, 500    from dual
 15    )
 16  select
 17    a.proc_code,
 18    a.adprc_pat_cost,
 19    p.proc_std_cost,
 20    round(avg(a.adprc_pat_cost) over (order by null), 2) avg_adm_cost,
 21    p.proc_std_cost - round(avg(a.adprc_pat_cost) over (order by null), 2) diff
 22  from adm_prc a left join procedure p on p.proc_code = a.proc_code;

 PROC_CODE ADPRC_PAT_COST PROC_STD_COST AVG_ADM_COST       DIFF
---------- -------------- ------------- ------------ ----------
     12055            250           250       154,62      95,38
     15510             75            75       154,62     -79,62
     29844         109,28                     154,62
     43111            355                     154,62
     19887             68                     154,62
     33335          70,45                     154,62

6 rows selected.

SQL>