Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing SQL query for getting maximum occurrence of a value in a column

Tags:

sql

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.

like image 433
anonymous Avatar asked Aug 02 '11 23:08

anonymous


People also ask

How do you find the most repeated value in a column SQL?

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.

Can I use max count ()) in SQL?

And the short answer to the above question is, no. You can't. It is not possible to nest aggregate functions.

How do you SELECT the maximum and minimum values of a column in SQL?

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.


2 Answers

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.

like image 148
Brian Hoover Avatar answered Oct 03 '22 17:10

Brian Hoover


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
like image 28
Dan Meier Avatar answered Oct 03 '22 17:10

Dan Meier