如何根据参与建筑项目的员工人数自动获得每位员工的收入金额。 已经尝试过这个,但错误。子查询返回超过1行。
SELECT e.name,
( SELECT( p.costs / count(r.employee_id))
FROM relation_employee r GROUP BY r.project_id ) AS revenue
FROM project p
INNER JOIN relation_employee r ON p.id = r.project_id
INNER JOIN employee e ON r.employee_id = e.id
表员工
id INT
名称VARCHAR
表项目
id INT
名称VARCHAR
费用INT
table relation_employee
employee_id INT
project_id INT
答案 0 :(得分:0)
不是在选择部分中使用相关子查询,而是可以将每个项目的员工数量作为要在from部分中使用的派生表获取,这对我来说至少看起来更清晰一些。查询可能如下所示:
-- revenue per employee
SELECT e.name, sum(p.costs * 1.0 / emp_count) AS revenue
FROM project p
INNER JOIN relation_employee r ON p.id = r.project_id
INNER JOIN (SELECT project_id, count(employee_id) emp_count FROM relation_employee GROUP BY project_id) c ON c.project_id = p.id
INNER JOIN employee e ON r.employee_id = e.id
GROUP BY e.name;
-- revenue per employee and project
SELECT
e.name as employee_name,
p.name as project_name,
sum(p.costs / emp_count) AS revenue
FROM project p
INNER JOIN relation_employee r ON p.id = r.project_id
INNER JOIN (SELECT project_id, count(employee_id) emp_count FROM relation_employee GROUP BY project_id) c ON c.project_id = p.id
INNER JOIN employee e ON r.employee_id = e.id
GROUP BY e.name, p.name;