如何编写“ GROUP BY”查询,以获取给定应用程序分配给用户的所有角色

时间:2019-04-05 21:34:10

标签: sql sql-server

我有两个表 User User_Roles 。一个用户可以具有多个角色。

用户表

User_Id  User_Name
1        Edward  
2        John 
3        Mark  

USER_ROLES TABLE

User_ID    Role
1          Admin
1          Writer
1          Form
2          Writer
3          Form
3          Writer

我想写一个查询,给我以下结果

User_ID    User_Name   Role
1          Edward      Admin, Writer,Form
2          John        Writer
3          Mark        Form,Writer

我尝试使用GROUP BY,我知道这是我可以获得结果的方法,但是我做得不好。

SELECT COUNT(T0.[User_Id]),T0.[User_Name],T1.[Role]      
FROM  USER T0  
INNER JOIN  USER_ROLES T1 ON T0.User_ID = T1.User_ID  
GROUP BY  T0.[User_Name], T1.[Role]

我将COUNT用于测试仅是因为当我对聚合函数进行GROUP BY时出现错误。

2 个答案:

答案 0 :(得分:1)

使用聚合和STRING_AGG()(从SQL Server 2017开始可用):

SELECT u.User_ID, u.User_Name, STRING_AGG(r.Role, ',') AS Roles
FROM  user u  
INNER JOIN  user_roles r ON r.User_Id = u.User_Id
GROUP BY u.User_ID, u.User_Name

注意:您可能希望对聚合的字符串进行排序,以便获得可预测的值,例如:

STRING_AGG(r.Role, ',') WITHIN GROUP (ORDER BY r.Role) AS Roles

答案 1 :(得分:0)

我们可以选择FOR XML / STUFF技巧:

  SELECT 
   U.USER_NAME,
   STUFF((SELECT ',' + UR.ROLE 
          FROM [USER_ROLES] UR
          WHERE UR.USER_ID = U.USER_ID
          FOR XML PATH('')), 1, 1, '') [ROLES]
FROM [USER] U
GROUP BY U.USER_NAME, U.USER_ID
ORDER BY 1

enter image description here

https://rextester.com/YLIJQ30828