【问题标题】:How to solve error group function not allowed如何解决错误组功能不允许
【发布时间】:2023-03-23 16:30:02
【问题描述】:

有两个表:

  • employeee(emp_id,emp_name,salary,dept_id) 和,
  • 部门(dept_id,dept_name)。

查询是查找员工人数最多的部门名称。我想出的查询是这样的

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:此处不允许使用群组功能

请在这里说明一下,我已经尝试了两天多。

【问题讨论】:

  • 在Oracle表表达式中必须有别名。

标签: sql oracle11g


【解决方案1】:

您正在尝试两次使用子查询的结果。为了多次(重新)使用它,您需要将其放入 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

【讨论】:

    【解决方案2】:

    一个解决方案是订购,然后只取第一条记录...

    像这样:

    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;
    

    【讨论】:

      猜你喜欢
      • 2018-11-13
      • 2013-01-28
      • 1970-01-01
      • 1970-01-01
      • 2021-09-24
      • 1970-01-01
      • 2019-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多