person_id | manager_id | name |
| | |
-------------------------------
查询以查找监督最大员工人数的经理姓名?
已添加:这是唯一的表格。是的自我引用。 DB是mysql。递归查询也可以。
答案 0 :(得分:5)
此查询返回经理的manager_id
和manager_name
以及最大雇员人数。
诀窍在HAVING
子句中,它允许聚合并计算多行。
SELECT manager_id,name, count(*)
FROM table
GROUP BY manager_id, name
HAVING max(count(*));
您可以阅读更多内容,但内容丰富w3schools.com HAVING clause
tutorial。
如果manager_id引用同一个表中的人员ID Svinto's answer might be more suitable。
答案 1 :(得分:4)
SELECT name
FROM table
WHERE person_id = (
SELECT manager_id
FROM table
GROUP BY manager_id
HAVING max(count(*)))
答案 2 :(得分:2)
我并不完全清楚你想要什么,所以如果这不是你想要的,请澄清你的问题。
如果存在平局,此查询仅返回其中一个经理:
SELECT T2.name FROM (
SELECT manager_id
FROM table1
WHERE manager_id IS NOT NULL
GROUP BY manager_id
ORDER BY count(*) DESC
LIMIT 1
) AS T1
JOIN table1 AS T2
ON T1.manager_id = T2.person_id
查询结果:
Bar
这是一个查询,在存在平局的情况下,获取具有绑定最大计数的所有经理:
SELECT name FROM (
SELECT manager_id, COUNT(*) AS C
FROM person
WHERE manager_id IS NOT NULL
GROUP BY manager_id) AS Counts
JOIN (
SELECT COUNT(*) AS C
FROM person
WHERE manager_id IS NOT NULL
GROUP BY manager_id
ORDER BY COUNT(*) DESC
LIMIT 1
) AS MaxCount
ON Counts.C = MaxCount.C
JOIN person
ON Counts.manager_id = person.person_id
第二个查询的结果:
Foo
Bar
这是我的测试数据:
CREATE TABLE Table1 (person_id int NOT NULL, manager_id nvarchar(100) NULL, name nvarchar(100) NOT NULL);
INSERT INTO Table1 (person_id, manager_id, name) VALUES
(1, NULL, 'Foo'),
(2, '1', 'Bar'),
(3, '1', 'Baz'),
(4, '2', 'Qux'),
(5, '2', 'Quux'),
(6, '3', 'Corge');
答案 3 :(得分:1)
假设manager_id引用了person_id和table的名称:table_name
SELECT name FROM (
SELECT manager_id
FROM table_name
GROUP BY manager_id
ORDER BY COUNT(*) DESC
LIMIT 1
) t
INNER JOIN table_name ON t.manager_id = table_name.person_id
修改强> 删除了HAVING MAX COUNT,在子查询中添加了ORDER BY COUNT DESC LIMIT 1