编写SQL查询以获取列中值的最大值

时间:2011-08-02 23:19:12

标签: sql

我有一张emp表,其中包含以下记录:

INSERT into emp(EmpId,Emp name, Manager)
Values(1,A,M1)
values(2,B,M1)
values(3,C,M2)
values(4,D,M3)

如何找到拥有最多员工人数的Manager?在这种情况下,输出应为M1。请帮忙。

8 个答案:

答案 0 :(得分:18)

select manager, count(*) as employees from emp
  group by manager
  order by count(*) desc

拿第一张唱片。根据您的SQL版本,您可以使用限制语句执行此操作。

答案 1 :(得分:4)

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

第一条记录将是拥有最多员工的经理。此外,基于db提供程序,您可以将结果集限制为1,因此您只能获得最高记录。这是使用sql server的一个例子:

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

答案 2 :(得分:4)

在SQL Server中......

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

Oracle有点不同......

SELECT Manager
FROM  ( SELECT Manager,
               COUNT(Manager) as "ManagerCount"
        FROM emp
        GROUP BY Manager
        ORDER BY "ManagerCount" DESC )
WHERE ROWNUM <= 1

答案 3 :(得分:2)

在Postgresql中,创建模式测试:

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

答案 4 :(得分:0)

如果你想要emp表中的行,请使用:

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

如果大多数员工存在平局,这也会返回多行。

答案 5 :(得分: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;

答案 6 :(得分:0)

经过SQL Server 2017

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

希望这个简单的查询会帮助很多人。

答案 7 :(得分:0)

如果使用的是Oracle数据库,则只需使用stats_mode函数,该函数将返回出现次数最多的单个值。

sleep(30)

此功能非常易于使用,而不是编写多行sql查询。