使用STUFFを有するものを返す必要があります
ステップ1:グループの役割(中注文)STUFFINGロールによって
ステップ2:STUFFユーザーごとグループ化された役割
declare @users table
(userID varchar(10), roleID varchar(10))
insert into @users
values ('User1','Role1'),
('User1','Role2'),
('User1','Role3'),
('User2','Role1'),
('User3','Role3'),
('User4','Role1'),
('User4','Role2'),
('User4','Role3'),
('User5','Role1'),
('User6','Role3'),
('User7','Role1')
-- group data according to role as the base table or you can dump this to a temp table
select y.userid, stuff((select ',' + roleid
from @users x
where x.userID = y.userID
order by x.roleID --- need to order by so it won't in random order
FOR XML PATH('')),1,1,'') as GroupRole
from @users y
group by y.userID
-- New structure
userid GroupRole
User1 Role1,Role2,Role3
User2 Role1
User3 Role3
User4 Role1,Role2,Role3
User5 Role1
User6 Role3
User7 Role1
-- OFFICIAL QUERY (not using temp tables otherwise reformat accordingly)
select stuff((select ',' + g.userID
from (select y.userid, stuff((select ',' + roleid --- can substitute with temp table
from @users x
where x.userID = y.userID
order by x.roleID
FOR XML PATH('')),1,1,'') as GroupRole
from @users y
group by y.userID) g
where g.GroupRole = a.GroupRole --- group matched from main query
FOR XML PATH('')),1,1,'') as Result
from --- reference table as bases of the grouping, can substitute with temp table
(select y.userid, stuff((select ',' + roleid
from @users x
where x.userID = y.userID
order by x.roleID
FOR XML PATH('')),1,1,'') as GroupRole
from @users y
group by y.userID) a
group by a.GroupRole
Result --
User2,User5,User7
User1,User4
User3,User6
ヒント - 使用STUFF – maSTAShuFu