SQL连接示例架构

时间:2015-08-19 21:16:48

标签: sql sql-server join

我有以下架构:

*Project*
ID(PK)  NAME
1       Alpha
2       Bravo
3       Charlie
4       Delta

*Employee*
ID(PK)  NAME
1       Kevin
2       Mike
3       Eric
4       Ira
5       Peter

*Project Assignment*
ID(PK)  ProjectID(FK)   EmployeeID(FK)
1       1               1
2       1               2
3       2               2
4       2               3
5       3               3
6       3               4
7       1               3

我想写一些查询:

1)显示所有已分配的项目及其团队成员。

期望的输出:

Project TeamMembers
Alpha   Eric
Alpha   Kevin
Alpha   Mike
Bravo   Eric
Bravo   Mike
Charlie Eric
Charlie Ira

2)仅显示Alpha项目及其团队成员,并显示按降序排序的团队成员的名称。

期望的输出:

ID      TeamMember
Alpha   Mike
Alpha   Kevin
Alpha   Eric

最简单的查询是什么样的?

其他问题:

每个项目的团队成员数量总和是什么?

期望的结果:

+-------------+-------------+
| ProjectName | NumMembers |
+-------------+-------------+
| Alpha       | 3           |
| Bravo       | 2           |
| Charlie     | 2           |
+-------------+-------------+

1 个答案:

答案 0 :(得分:0)

create table Project (ID int,  NAME varchar(50));

insert into Project values
(1, 'Alpha'),
(2, 'Bravo'),
(3, 'Charlie'),
(4, 'Delta');

create table Employee (ID int,  NAME varchar(50));

insert into Employee values
(1, 'Kevin'), 
(2, 'Mike'),
(3, 'Eric'),
(4, 'Ira'),
(5, 'Peter');

create table Project_Assignment (ID int,  ProjectID int,  EmployeeID int);

insert into Project_Assignment values
(1, 1,  1),
(2, 1,  2),
(3, 2,  2),
(4, 2,  3),
(5, 3,  3),
(6, 3,  4),
(7, 1,  3);

解决方案#1:

您需要将Project_Assignment表加入ProjectEmployee表,分别获取两列:

select p.name as projectname,
       e.name as TeamMembers   
from project_assignment pa
join project p on pa.projectid = p.id
join employee e on pa.employeeid = e.id
order by projectname, TeamMembers desc;   

<强>结果:

+-------------+-------------+
| projectname | TeamMembers |
+-------------+-------------+
| Alpha       | Mike        |
| Alpha       | Kevin       |
| Alpha       | Eric        |
| Bravo       | Mike        |
| Bravo       | Eric        |
| Charlie     | Ira         |
| Charlie     | Eric        |
+-------------+-------------+

SQL Fiddle Demo

解决方案#2:

在上述查询中添加where子句,仅过滤Alpha项目:

select p.name as projectname,
       e.name as TeamMembers   
from project_assignment pa
join project p on pa.projectid = p.id
join employee e on pa.employeeid = e.id
where p.name = 'Alpha'
order by projectname, TeamMembers desc;

<强>结果:

+-------------+-------------+
| projectname | TeamMembers |
+-------------+-------------+
| Alpha       | Mike        |
| Alpha       | Kevin       |
| Alpha       | Eric        |
+-------------+-------------+

SQL Fiddle Demo 2