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

后端 未结 8 545
遇见更好的自我
遇见更好的自我 2021-01-02 02:44

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)         


        
相关标签:
8条回答
  • 2021-01-02 03:21
    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.

    0 讨论(0)
  • 2021-01-02 03:23

    If you want the row from the emp table, use this:

    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 );
    

    This will also return multiple rows in case there is a tie for the most number of employees.

    0 讨论(0)
  • 2021-01-02 03:25
    SELECT
        Manager,
        count(Manager) AS 'Num of Emps'
    FROM
        emp
    GROUP BY
        Manager
    ORDER BY
        'Num of Emps' DESC
    

    The first record will be the manager with the most employees. Also, based on the db provider, you can limit the result set to 1, so you only get the highest record. Here's an example using sql server:

      SELECT
        TOP 1 Manager,
        count(Manager) AS 'Num of Emps'
    FROM
        emp
    GROUP BY
        Manager
    ORDER BY
        'Num of Emps' DESC
    
    0 讨论(0)
  • 2021-01-02 03:35

    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
    
    0 讨论(0)
  • 2021-01-02 03:38

    In Postgresql, create schema Test:

    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
    
    0 讨论(0)
  • 2021-01-02 03:40

    Tested With SQL Server 2017

    Select TOP 1 City, Count(City) AS 'MAX_COUNT' FROM Customer Group By City Order By 'MAX_COUNT' DESC;
    

    Hope this simple query will help many one.

    0 讨论(0)
提交回复
热议问题