【发布时间】:2021-02-12 11:26:52
【问题描述】:
我想尝试找到教过最多课程的员工作为职位Teacher。所以在这里我想打印出Nick,因为他以Teacher 的身份教过最多的课程。
但是,我得到了错误:
错误:列“e.name”必须出现在 GROUP BY 子句中或用于聚合函数位置: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
【问题讨论】:
标签: sql postgresql count sql-order-by inner-join