I have an emp
table with the records below:
INSERT into emp(EmpId,Emp name, Manager)
Values(1,A,M1)
values(2,B,M1)
values(3,C,M2)
values(4,D,M3)
How can I find the Manager
having the maximum number of employees under him? In this case, output should be M1
. Please help.
select cnt1. column_name from (select COUNT(*) as total, column_name from table_name group by column_name) cnt1, (select MAX(total) as maxtotal from (select COUNT(*) as total, column_name from table_name group by column_name)) cnt2 where cnt1.
And the short answer to the above question is, no. You can't. It is not possible to nest aggregate functions.
To ask SQL Server about the minimum and maximum values in a column, we use the following syntax: SELECT MIN(column_name) FROM table_name; SELECT MAX(column_name) FROM table_name; When we use this syntax, SQL Server returns a single value.
select manager, count(*) as employees from emp
group by manager
order by count(*) desc
Take the first record. Depending on your SQL version, you can do this with a limit statement.
In SQL Server...
SELECT TOP 1 Manager
FROM ( SELECT Manager,
COUNT(Manager) as "ManagerCount"
FROM emp
GROUP BY Manager
ORDER BY "ManagerCount" DESC )
Oracle is a bit different...
SELECT Manager
FROM ( SELECT Manager,
COUNT(Manager) as "ManagerCount"
FROM emp
GROUP BY Manager
ORDER BY "ManagerCount" DESC )
WHERE ROWNUM <= 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With