我有两个表employee表和employee dependency表。 员工就像下面这样。
insert into E values(1,'Adam')
insert into E values(2,'Bob')
insert into E values(3,'Candy')
insert into E values(4,'Doug')
insert into E values(5,'Earl')
insert into E values(6,'Fran')
员工依赖关系表如下所示
insert into Ed values(3,'2')
insert into Ed values(3,'5')
insert into Ed values(2,'1')
insert into Ed values(2,'4')
insert into Ed values(5,'6')
我需要找到如下的依赖列表
Eid Ename Dname
3 Candy Bob,Fran
请帮助我找到上述内容。
答案 0 :(得分:1)
设定:
create table E(id int , name varchar(100))
insert into E values(1,'Adam')
insert into E values(2,'Bob')
insert into E values(3,'Candy')
insert into E values(4,'Doug')
insert into E values(5,'Earl')
insert into E values(6,'Fran')
create table Ed(id1 int, id2 int)
insert into Ed values(3,2)
insert into Ed values(3,5)
insert into Ed values(2,1)
insert into Ed values(2,4)
insert into Ed values(5,6)
查询:
select Name,
stuff((select ',' + e1.name
from Ed
join E e1 on
Ed.id2 = e1.id
where Ed.id1 = E.id
for xml path('')), 1, 1, '') as Dependents
from E
结果:
Name Dependents
---------- --------------
Adam NULL
Bob Adam,Doug
Candy Bob,Earl
Doug NULL
Earl Fran
Fran NULL
如果您只需要展示那些有家属的人:
select *
from
(
select Name,
stuff((select ',' + e1.name
from Ed
join E e1 on
Ed.id2 = e1.id
where Ed.id1 = E.id
for xml path('')), 1, 1, '') as Dependents
from E
) tt
where Dependents is not null