ORA-00978:嵌套分组函数没有 GROUP BY /ORA-00937:不是单分组函数---解决思路

今天在操作数据库时遇到了oracle的报错,错误类型为ORA-00978/ORA-00937,经与同事讨论研究之后发现一个特别容易犯错的点。

首先,我的目的是从一个表中取出一列数值,然后对这一列数值进行求和并平均

取数SQL为:select b.vendor from t_cm_networknode b where b.vendor is not null

求和并平均SQL为:select avg(sum(f.vendor)) from (select b.vendor from t_cm_networknode b where b.vendor is not null) f   (不要质疑为什么不在取数时直接进行sum avg--!)

取数SQL结果如下:


求和平均SQL却报错,错误类型如下:

然后查询ORA-00978原因后,修改SQL为:

select f.cloud ,avg(sum(f.vendor))  from (select 12321 as cloud, b.vendor from t_cm_networknode b where b.vendor is not null) f  group by cloud

运行扔报错,错误提示为ORA-00937:


然后继续修改SQL如下:

select avg(sum(f.vendor)) from (select b.vendor from t_cm_networknode b where b.vendor is not null) f group by vendor

结果如下:


值出来了,但似乎是求和,并没有平均

然后继续修改SQL为:

select sum(f.vendor)/count(f.vendor) from (select b.vendor from t_cm_networknode b where b.vendor is not null) f

结果为:


好了,这就是我们想要的结果,想必看到这里,对于错误的原因应该也清楚了。

错误总结:

oralce中聚合函数(count、max、min、sum、avg等)在使用时,必须指定其聚合的维度对象,也就是必须通过group by来实现其聚合对象的分类,若聚合结果只有一条数值,则不需要group by指定聚合对象。

本次报错的原因在于avg(sum())时,sum()后就是一条数据,avg()的对象只有一条,故报错ORA--00978,后续增加虽增加了group by cloud ,但avg()也是一条,无法对应多个cloud,故报错ORA--00937,

在针对结果只有一条数据的汇聚时,用sum()/count()即可。

猜你喜欢

转载自blog.csdn.net/walking_visitor/article/details/80908480