-1

我对 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
4

3 回答 3

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;
于 2012-10-18T12:52:27.793 回答
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

于 2012-10-18T12:57:54.343 回答
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
于 2012-10-18T12:33:44.190 回答