在大多数人的监督下找到manager_id

时间:2018-10-15 20:51:40

标签: sql oracle oracle11g

我在manager_id下显示最多的人时遇到麻烦。答案是manager_id = 100,但我似乎无法制作一个显示它的SQL。以下是创建并提供给我的2个表格。

CREATE TABLE departments
    ( department_id    NUMBER(4)
    , department_name  VARCHAR2(30)
    CONSTRAINT  dept_name_nn  NOT NULL
    , manager_id       NUMBER(6)
    , location_id      NUMBER(4)
    ) ;

CREATE TABLE employees
    ( employee_id    NUMBER(6)
    , first_name     VARCHAR2(20)
    , last_name      VARCHAR2(25)
     CONSTRAINT     emp_last_name_nn  NOT NULL
    , email          VARCHAR2(25)
    CONSTRAINT     emp_email_nn  NOT NULL
    , phone_number   VARCHAR2(20)
    , hire_date      DATE
    CONSTRAINT     emp_hire_date_nn  NOT NULL
    , job_id         VARCHAR2(10)
    CONSTRAINT     emp_job_nn  NOT NULL
    , salary         NUMBER(8,2)
    , commission_pct NUMBER(2,2)
    , manager_id     NUMBER(6)
    , department_id  NUMBER(4)
    , CONSTRAINT     emp_salary_min
                     CHECK (salary > 0) 
    , CONSTRAINT     emp_email_uk
                     UNIQUE (email)
    ) ;

下面是我的代码,我试图将两个表employeesdepartments结合在一起,以在它们之间找到manager_id的次数最多。

每次我尝试运行sql块时,都会出现类似"ORA-00918: column ambiguously defined"的错误,或者Limit 1出现问题

SELECT COUNT(Manager_id) into v_manager_id, 
FROM departments d
RIGHT JOIN employees e
ON d.manager_id = e.manager_id
GROUP BY Manager_id
ORDER BY COUNT(Manager_id) DESC
LIMIT 1;

3 个答案:

答案 0 :(得分:0)

您应该宁愿选择count(employee_id)...按manager_id分组,以便为​​某个经理下的所有雇员显示该计数,然后检查该经理下的最大人数是否 否则是别名或限定词问题,您应该将manager_id命名为一些别名。

答案 1 :(得分:0)

这将起作用:

select manager_id 
from (select manager_id,count(*)  
      from employees  
      group by manager_id 
      order by 
      count(*) desc)
where rownum<=1 ;

您还可以像这样使用嵌套子查询:

create table ns_231(col1 number,col2 number);

insert into ns_231 values(1,1);
insert into ns_231 values(2,3);
insert into ns_231 values(3,3);
insert into ns_231 values(1,2);
insert into ns_231 values(2,5);
insert into ns_231 values(2,1);
insert into ns_231 values(3,1);
insert into ns_231 values(1,4);

SELECT * FROM ns_231;
commit;
select col1 from (select col1,count(*) from ns_231  group by col1 order by count(*) desc) where rownum<=1 ;

select col1 from ns_231 group by col1
having count(*)=(select max(total) from (select count(*) as total from 
ns_231 group by col1));

输出:

1
2

对于您的表,查询为:

select manager_id from employees group by manager_id
having count(*)=(select max(total) from (select count(*) as total from 
employees group by manager_id));

答案 2 :(得分:-1)

我认为您需要在manager_id中添加限定符,因为它同时出现在两个表中

SELECT COUNT(d.Manager_id) into v_manager_id, 
FROM departments d
RIGHT JOIN employees e
ON d.manager_id = e.manager_id
GROUP BY d.Manager_id
ORDER BY COUNT(d.Manager_id) DESC
LIMIT 1;