我有两个表User,并UserRoles在SQL Server中.Usertable有基本的用户信息,例如UserId,Nameetc,并且UserRoles有像这样的列UserId,RoleName.这两个表之间存在一对多的关系,即一个用户可以拥有多个角色.
用户
UserId Name
1 A
2 B
3 C
Run Code Online (Sandbox Code Playgroud)
的UserRole
UserId Rolename
1 Manager
1 Event Organiser
2 Supervisor
2 Employee
2 Some otherRole
Run Code Online (Sandbox Code Playgroud)
我需要在sql中编写一个查询,它将返回如下.即将一个到多个记录连接成一个字符串
UserId Roles
1 Manager,Event Organiser
2 Supervisor,Employee,Some otherRole
Run Code Online (Sandbox Code Playgroud)
您必须使用以下2 SQL功能
XML路径 - 用于连接
逗号分离的东西
select UserId,
stuff((select ',' + t2.Rolename
from UserRoles t2 where t1.UserId = t2.UserId
for xml path('')),1,1,'') Roles
from UserRoles t1
group by UserId
Run Code Online (Sandbox Code Playgroud)