2017-06-12 7 views
1

SQL Server 2008 SP4共通のセキュリティロールグループを持つすべてのユーザーの検索

共通のセキュリティロールのコレクションを持つすべてのユーザーを特定してデータを調べようとしています。一致のために、彼らはまったく同じセキュリティロールのコレクションを持っています。例データ

User_Roles

UserID RoleID 
------ ------ 
User1 Role1 
User1 Role2 
User1 Role3 
User2 Role1 
User3 Role3 
User4 Role1 
User4 Role2 
User4 Role3 
User5 Role1 
User6 Role3 
User7 Role1 

結果セットが同じグループ化されたコレクション

User1, User4 -- users with ROLE1,2&3 
User2, User5, User7 -- users with ROLE1 ONLY 
User3, User6 -- users with ROLE3 ONLY 
+0

ヒント - 使用STUFF – maSTAShuFu

答えて

0

使用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 
+0

これは私に必要なものを正確に教えてくれます。完璧なおかげです。 –

0

あなたはセットベースの操作でこれを行うことができます。

with ur as (
     select ur.*, count(*) over (partition by userid) as cnt 
     from user_roles ur 
    ) 
select ur1.userid, ur2.userid 
from ur ur1 join 
    ur ur2 
    on ur1.roleid = ur2.roleid and 
     ur1.cnt = ur2.cnt and 
     ur1.userid < ur2.userid 
group by ur1.userid, ur2.userid, ur1.cnt 
having count(*) = ur1.cnt; 

これは、すべての役割は、2人のユーザ間、彼らは役割の数が同じであることと一致することを確認します。

+0

これはちょうど最初の部分です..これを完了するには比較的彼らをスタフしています – maSTAShuFu

+0

ゴードンこれも私のために働く。上の答えはちょうど私が必要としたもののための少し良いフォーマットでデータを提示しました。ご協力いただきありがとうございます。これは非常にきれいな解決策です。 –

関連する問題