如何找到教得最多的人 类

How to I find the person who has taught the most classes

我想尝试找到教过最多 类 的员工作为职位 Teacher。所以在此我想打印出Nick,因为他教过最多类作为一个Teacher

但是,我收到错误消息:

ERROR: column "e.name" must appear in the GROUP BY clause or be used in an aggregate function Position: 24

CREATE TABLE employees (
  id integer primary key,
  name text
);

CREATE TABLE positions (
  id integer primary key,
  name text
);

CREATE TABLE teaches (
  id integer primary key,
  class text,
  employee integer,
  position integer,
  foreign key (employee) references employees(id),
  foreign key (position) references positions(id)
);

INSERT INTO employees (id, name) VALUES
(1, 'Clive'), (2, 'Johnny'), (3, 'Sam'), (4, 'Nick');

INSERT INTO positions (id, name) VALUES
(1, 'Assistant'), (2, 'Teacher'), (3, 'CEO'), (4, 'Manager');

INSERT INTO teaches (id, class, employee, position) VALUES
(1, 'Dancing', 1, 1), (2, 'Gardening', 1, 2),
(3, 'Dancing', 1, 2), (4, 'Baking', 4, 2),
(5, 'Gardening', 4, 2), (6, 'Gardening', 4, 2),
(7, 'Baseball', 4, 1), (8, 'Baseball', 2, 1),
(9, 'Baseball', 4, 2);

我正在尝试使用的 SQL 语句:

SELECT count(t.class), e.name
FROM positions p
JOIN teaches t
ON p.id = t.position
JOIN employees e
ON e.id = t.employee
WHERE p.name = 'Teacher'
GROUP BY t.employee;

我一直在 sql fiddle 上研究这个: http://www.sqlfiddle.com/#!17/a8e19c/3

您的查询看起来不错。您只需要修复 GROUP BY 子句,使其与 SELECT 子句中的列保持一致。然后 ORDER BYLIMIT:

SELECT count(*) cnt_classes, e.name
FROM positions p 
INNER JOIN teaches   t ON p.id = t.position
INNER JOIN employees e ON e.id = t.employee
WHERE p.name = 'Teacher' 
GROUP BY e.id              --> primary key of "employees"
ORDER BY cnt_classes DESC  --> order by descending count of classes
LIMIT 1                    --> keep the first row only

在您的 select 中,您正在使用聚合 COUNT 计算每个组中的所有行 (GROUP BY t.employee) 但您不聚合 e.name.

所以对于 Nick,基本上 select 每行 4 行,每行 class 有两列 - class 姓名和老师姓名。然后你要求服务器计算 Nicks 组中的 class 个名字(按他的员工 ID),这将 4 行聚合成一个值为 4 但你没有对教师姓名做任何事情所以你留下了无效的结构classes 计数列有 1 行,教师姓名有 4 行。其他老师也一样。这就是服务器所抱怨的。解决这个问题的最简单方法是将 e.name 添加到 GROUP BY,这会将相同值的 4 行压缩为一个。

要获得教授最多 classes 的老师,您只需按 class 计数降序对结果进行排序并将结果计数限制为 1。这将为您提供具有最高 class计数。

已更新 fiddle:http://www.sqlfiddle.com/#!17/a8e19c/7

您收到错误是因为您需要拥有您选择的每一列(e.name 在本例中的 GROUP BY 子句中,否则 SQL 不知道如何分组并 return 该列的计数。如果您想 return 拥有最多的人,您还需要使用 TOP(1) 和排序依据。

SELECT TOP(1) count(*), e.name
FROM teaches t 
INNER JOIN positions p ON t.position = p.id
INNER JOIN employees e ON e.id = t.employee
WHERE p.name = 'Teacher'
GROUP BY e.name
ORDER BY count(*) DESC;