sql - How to user grouping sets as keys for the next grouping
问题描述
We have the following table:
DECLARE @UserGroup TABLE (UserId int, GroupId int)
insert into @UserGroup values (1,1) -- User 1 belongs to Group 1
insert into @UserGroup values (1,2) -- User 1 belongs to Group 2
insert into @UserGroup values (2,1) -- User 2 belongs to Group 1
insert into @UserGroup values (2,2) -- User 2 belongs to Group 2
insert into @UserGroup values (3,1) -- User 3 belongs to Group 1
insert into @UserGroup values (4,4) -- User 4 belongs to Group 4
We can see that User 1 and User 2 belong to the same two groups Group 1 and Group 2. User 3 belongs to Group 1 only and User 4 belongs to Group 4. What I'm trying to achieve should look like something below:
Key(group combination) | User Id
(Group1,Group2) | Either User 1 or User 2
(Group1) | User 3 only
(Group4) | User 4 only
Basically, for each combination of groups we have users for, I want to select ANY user from that group. Just to give more context, I need to select one user from a combination of groups to do some testing related to security since security is set for groups and not users.
I believe the following query does the job:
;WITH groupKeysAndUsers as
(
select
STRING_AGG(ug1.GroupId, ',') WITHIN GROUP (ORDER BY ug1.GroupId) as GroupKey,
ug1.UserId
from @UserGroup ug1
group by ug1.UserId
)
select GroupKey, min(UserId) -- I use min to select any user from the grouping set
from groupKeysAndUsers
group by GroupKey
I wonder if there is a better way(faster and/or easier to consume) to achieve the same result without using STRING_AGG
.
解决方案
推荐阅读
- javascript - 如何将浏览器作为具有量角器多功能的参数传递?
- javascript - rxjs 观察超时的正确方法
- c# - UWP:如何从 Documents 文件夹的子文件夹中获取所有文本文件名的列表
- google-cloud-platform - 使用 gsutil 仅上传 html 文件?
- matlab - 如何在Matlab中以有效的方式将一个值分配给对象列表?
- react-native - React native 或 Flutter 是否支持按需资源?
- react-native - 在 react native expo 应用程序中使用 Formik 时出错
- javascript - 使用 jQuery 的 attr("src", url) 在 iframe 中加载 url 时尝试捕获
- sql - 在多行满足连接条件的情况下随机连接
- git - 如何在本地查看自己在 Gogs 中的文件?