尝试以下查询:
select distinct Users,
STUFF(
(
select ', ' + d.Department FROM @temp d
where t.Users=d.Users
group by d.Department for xml path('')
), 1, 2, '') as Departments
from @temp t
执行:
Declare @temp Table(
ID int,
Users varchar(50),
Department varchar(50)
)
insert into @temp
(ID,Users,Department)
values
(1,'User1','Admin')
insert into @temp
(ID,Users,Department)
values
(2,'User1','Accounts')
insert into @temp
(ID,Users,Department)
values
(3,'User2','Finance')
insert into @temp
(ID,Users,Department)
values
(4,'User3','Sales')
insert into @temp
(ID,Users,Department)
values
(5,'User3','Finance')
select distinct Users,
STUFF(
(
select ', ' + d.Department FROM @temp d
where t.Users=d.Users
group by d.Department for xml path('')
), 1, 2, '') as Departments
from @temp t
结果将是: