我在尝试打印department_id,department_name和每个部门的工资总额时遇到了一些问题,但我无法弄清楚原因。我收到错误:00979 - "不是GROUP BY表达式"
SELECT d.department_id, d.department_name, SUM(e.salary)
FROM departments d, employees e
WHERE d.department_id = e.department_id
GROUP BY d.department_id;
答案 0 :(得分:5)
只需将name
添加到group by
表达式即可。在此过程中,还要修复查询以使用显式join
语法:
SELECT d.department_id, d.department_name, SUM(e.salary)
FROM departments d JOIN
employees e
ON d.department_id = e.department_id
GROUP BY d.department_id, d.department_name;
虽然您没有问,但我会指出您的查询版本确实有意义且符合ANSI标准(尽管大多数数据库不支持此功能)。您正在通过主键进行聚合,因此允许引入其他列 - 尽管Oracle不支持此功能。
答案 1 :(得分:1)
SELECT d.department_id, d.department_name, SUM(e.salary)
FROM departments d, employees e
WHERE d.department_id = e.department_id
GROUP BY d.department_id, d.department_name;
只需在group by子句中添加department_name列。
答案 2 :(得分:1)
或者,您也可以使用MIN()
或MAX()
汇总部门名称:
SELECT d.department_id, MAX(d.department_name) AS department_name
, SUM(e.salary) AS department_salary
FROM departments d INNER JOIN employees e
ON d.department_id = e.department_id
GROUP BY d.department_id;
请注意,我将您的语法从旧的ANSI标准更新为更新的标准。如果您更喜欢较旧的语法(就像我一样),那么只需使用它:
SELECT d.department_id, MAX(d.department_name) AS department_name
, SUM(e.salary) AS department_salary
FROM departments d, employees e
WHERE d.department_id = e.department_id
GROUP BY d.department_id;