Sql 如何解决不允许的错误组函数
有两个表格:Sql 如何解决不允许的错误组函数,sql,oracle11g,Sql,Oracle11g,有两个表格: 员工(员工id、员工姓名、工资、部门id)和 部门(部门id、部门名称) 查询的目的是查找员工人数最多的部门名称。我提出的问题是 select dept_name from department where dept_id = (select dept_id from (select dept_id,count(dept_id) numbers from employee group by dept_id)
- 员工(员工id、员工姓名、工资、部门id)和
- 部门(部门id、部门名称)
select dept_name from department
where dept_id = (select dept_id from (select dept_id,count(dept_id) numbers
from employee group by dept_id)
where numbers = max(numbers));
显示的错误如下所示
ORA-00934:此处不允许使用组功能
请说明一下,我已经尝试了两天多。您正在尝试使用子查询的结果两次。为了多次(重新)使用它,您需要将其放入CTE(公共表表达式)中。一旦这样做,查询就会变得更容易 例如,您可以将查询改为:
with
x as (
select dept_id,count(dept_id) as numbers from employee group by dept_id
),
y as (
select dept_id from x where numbers = (select max(numbers) from x)
)
select dept_name
from department d
join y on y.dept_id = d.dept_id
一种解决方法是订购,然后只取第一条记录 像这样:
select * from
(
select d.dept_name, count(e.id)
from department d, employee e
where e.dept_id = d.dept_id
group by d.dept_name
order by count(e.id) desc
)
where rownum = 1;
在Oracle表中,表达式必须具有别名。