Oracle SQL:ORA-00937:不是单组组函数
Posted
技术标签:
【中文标题】Oracle SQL:ORA-00937:不是单组组函数【英文标题】:Oracle SQL: ORA-00937: not a single-group group function 【发布时间】:2018-10-19 20:13:58 【问题描述】:我正在尝试计算 ID 为 118 的外科医生在 2016 年赚取的金额
通过使用代码:
select (sum(count(*) * professional_fee)) AS
"Total amount earned by 118"
from operation, operation_type, staff
where operation.actual_op = operation_type.op_code
and staff.person_id = operation.surgeon
and surgeon = 118
and extract(YEAR from op_date) = 2016
group by professional_fee;
我可以得到9600的正确结果
但是当我添加时
select (sum(count(*) * professional_fee) **+ annual_basic_salary**) AS
"Total amount earned by 118"
from operation, operation_type, staff
where operation.actual_op = operation_type.op_code
and staff.person_id = operation.surgeon
and surgeon = 118
and extract(YEAR from op_date) = 2016
group by professional_fee, **annual_basic_salary**;
我得到错误:ORA-00937: not a single-group group function
这里是使用的表格:
Staff
Operation
Operation_type
【问题讨论】:
【参考方案1】:这样的事情可以吗? (我缩短了你的表格;不想打字太多。)
我没有修复您的查询,而是写了一个新的。我不知道你为什么使用 COUNT 函数;你算什么?如果您确实想使用您的代码,请查看@LoztInSpace 写的内容以及我在该答案下的评论。
另外,我尝试正确连接表并为所有列使用表别名。我建议你以后也这样做。没有它,很难猜测这些列属于哪个表。
SQL> with
2 operation (actual_op, surgeon, op_date) as
3 (select 'LO', 118, date '2016-05-06' from dual union all
4 select 'HT', 118, date '2016-05-06' from dual union all
5 select 'TS', 118, date '2016-05-07' from dual union all
6 select 'TS', 111, date '2016-01-01' from dual
7 ),
8 operation_type (op_code, operation_name, professional_fee) as
9 (select 'LO', 'Lobotomy' , 1050 from dual union all
10 select 'HT', 'Heart Transplant', 7500 from dual union all
11 select 'TS', 'Tonsillectomy' , 1050 from dual union all
12 select 'AP', 'Appendicectomy', 750 from dual
13 ),
14 staff (person_id, annual_basic_salary) as
15 (select 118, 20000 from dual union all
16 select 111, 8000 from dual
17 )
18 select sum(t.professional_fee) + s.annual_basic_salary as result
19 from operation_type t join operation o on o.actual_op = t.op_code
20 join staff s on s.person_id = o.surgeon
21 where s.person_id = 118
22 and extract(year from o.op_date) = 2016
23 group by s.annual_basic_salary;
RESULT
----------
29600
SQL>
【讨论】:
我使用 count 函数将每种操作的数量乘以其各自的专业费用,但我意识到这不是必需的。感谢您的帮助!【参考方案2】:我不明白你的组。你确定要吗?
直观上看起来像 + max(annual_basic_salary)
没有分组:
select (sum(professional_fee))+max(annual_basic_salary) AS
"Total amount earned by 118"
from operation, operation_type, staff
where operation.actual_op = operation_type.op_code
and staff.person_id = operation.surgeon
and surgeon = 118
and extract(year from o.op_date) = 2016
【讨论】:
恐怕你的直觉现在不能正常工作;它仍然会返回相同的 ORA-00937,除非您 DO 将 annual_basic_salary 包含到 GROUP BY 子句中。 如果您使用 MAX 将其设为聚合,则不会。无论如何,我认为 group by 在这种情况下没有任何意义,因为如果不选择您的组,您就无法判断哪个值适用于哪个组! 你试过了吗?我做到了;这就是我写评论的原因。但是是的 - 我同意,查询本身是错误的。附:我的数据库是 11gXE;也许您的建议适用于其他版本。以上是关于Oracle SQL:ORA-00937:不是单组组函数的主要内容,如果未能解决你的问题,请参考以下文章