我对SQL完全不熟悉。我创建了以下表格。
Employee
- employee_id
- employee_name
Projects
- project_id
- project_name
Roles
- role_id
- role_name
Employee_project_role
- employee_id
- project_id
- role_id
我必须编写一个查询:列出具有不同角色数量的员工,并列出角色。 即如果一名员工(emp1)在一个项目中担任团队负责人(TL),在另外两个不同的项目中担任测试员(TEST),则输出应为:
employee_name count Role
---------------------------
emp1 1 TL
emp1 2 TEST
答案 0 :(得分:3)
尝试,
SELECT COUNT(my_table.*), my_table.employee_name, my_table.role
FROM
(SELECT r.role_name as role, e.employee_name as employee_name
FROM employee e
JOIN employee_project_role epr ON epr.employee_id = e.employee_id
JOIN roles r ON r.role_id = epr.role_id) my_table
GROUP BY my_table.employee_name, my_table.role;
答案 1 :(得分:1)
select
E.employee_name,
count(*) as cnt,
R.role_name
from Employee_project_role as EPR
left outer join Employee as E on E.employee_id = EPR.employee_id
left outer join Roles as R on R.role_id = EPR.role_id
group by E.employee_name, R.role_name
答案 2 :(得分:1)
使用分组来累计项目总和。
SELECT emp.employee_name,count(proj.project_name),role.role_name
FROM employee emp , project proj , role role , employee_project_role main
WHERE emp.employee_id = main.employee_id
AND proj.project_id = main.project_id
AND role.role_id = main.role_id
group by emp.employee_name , role.role_name
在此处查看SqlFiddle