简体   繁体   English

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

[英]How To Write a 'GROUP BY' query to get all the Roles assigned to User for a given applicatoin

I have two tables User and User_Roles . 我有两个表UserUser_Roles A User can have multiple Roles. 一个用户可以具有多个角色。

USER TABLE 用户表

User_Id  User_Name
1        Edward  
2        John 
3        Mark  

USER_ROLES TABLE USER_ROLES表

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

I want to write a query that gives me the following result 我想写一个查询,给我以下结果

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

I have tried using a GROUP BY and I know this is how I can get the result but I am just not doing it right. 我尝试使用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]

I am using a COUNT for test purpose only because when I do a GROUP BY with an aggregate function , I get an error. 我将COUNT用于测试仅是因为当我使用聚合函数执行GROUP BY时,会出现错误。

Use aggregation and STRING_AGG() (available starting SQL Server 2017): 使用聚合和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

NB: you might want to order the aggregated strings so you do get predictable values, like: 注意:您可能想对聚合字符串进行排序,以便获得可预测的值,例如:

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

An alternative is to us the FOR XML / STUFF trick : 对我们来说,另一种选择是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

在此处输入图片说明

https://rextester.com/YLIJQ30828 https://rextester.com/YLIJQ30828

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM