2011-08-02 24 views

Respuesta

4
SELECT 
    Manager, 
    count(Manager) AS 'Num of Emps' 
FROM 
    emp 
GROUP BY 
    Manager 
ORDER BY 
    'Num of Emps' DESC 

El primer registro será el administrador con la mayor cantidad de empleados. Además, según el proveedor de db, puede limitar el conjunto de resultados a 1, por lo que solo obtiene el registro más alto. Aquí está un ejemplo de uso del servidor SQL:

SELECT 
    TOP 1 Manager, 
    count(Manager) AS 'Num of Emps' 
FROM 
    emp 
GROUP BY 
    Manager 
ORDER BY 
    'Num of Emps' DESC 
13
select manager, count(*) as employees from emp 
    group by manager 
    order by count(*) desc 

Tome el primer registro. Dependiendo de su versión SQL, puede hacer esto con una declaración de límite.

+0

Gracias . ¡Esto hizo que mi día fuera mucho más fácil! –

0

Si desea que la fila de la tabla emp, utilice esto:

select * from emp 
where empid in (select manager from 
    (select manager, count(*) 
    from emp 
    group by 1 
    having count(*) = (select max(count) from (select manager, count(*) as count from emp group by 1) x) 
    ) y); 

Esto también volverá varias filas en caso de que haya un empate para el mayor número de empleados.

4

En SQL Server ...

SELECT TOP 1 Manager 
FROM (SELECT Manager, 
       COUNT(Manager) as "ManagerCount" 
     FROM emp 
     GROUP BY Manager 
     ORDER BY "ManagerCount" DESC) 

Oracle es un poco diferente ...

SELECT Manager 
FROM (SELECT Manager, 
       COUNT(Manager) as "ManagerCount" 
     FROM emp 
     GROUP BY Manager 
     ORDER BY "ManagerCount" DESC) 
WHERE ROWNUM <= 1 
0
SELECT 
    count(e.last_name) count, 
    d.last_name 
FROM 
    employees e 
LEFT OUTER JOIN employees d ON e.manager_id = d.employee_id 
GROUP BY 
    d.last_name 
ORDER BY 
    count DESC; 
2

en PostgreSQL, crear Prueba esquema:

create table Test.Employee (Emp_id numeric, manager_id numeric, Manager_name varchar(20)); 

insert into Test.Employee(emp_id, manager_id, manager_name) values(1, 3, 'A'), (2, 3, 'A'), (3, 3, 'A'), (4, 3, 'A'), (5, 11, 'B'), (6, 12, 'C'), (7, 11, 'B'); 

select manager_name from (select count(manager_id) as mcount, manager_name from test.employee group by manager_name order by mcount DESC) AS TEMP limit 1 
Cuestiones relacionadas