sql-server - 在 SQL Server 的 string_agg 函数中使用 distinct
问题描述
假设我有这张桌子:
area room
Area_1 Room1
Area_1 Room2
Area_1 Room3
Area_2 Room4
Area_2 Room5
我想得到这个结果
areas | rooms
-----------------+---------------------------------------
Area_1 | Area_2 | Room2 | Room3 | Room1 | Room5 | Room4
这是我到目前为止为这个例子所做的:
select
STRING_AGG(area , ' | ') as areas,
STRING_AGG(rooms, ' | ' ) as rooms
from (
select area, STRING_AGG(room, ' | ') as rooms
from
(
select *
from (
values
('Area_1','Room1'),
('Area_1','Room2'),
('Area_1','Room3'),
('Area_2','Room4'),
('Area_2','Room5')
) as a(area, room)
) example
group by area
) c
在 PostgreSQL 中,可以使用string_agg
具有 distinct 的函数,但在 SQL Server 中,这似乎不可用,这就是为什么我必须使用一个子查询来对区域进行分组,并在外部选择中最终得到预期结果的原因。我想知道是否可以在一次选择中获得此输出。在此示例中,我只有两列,但在实际情况中,我有几列需要以相同的方式进行分组,并且对于每一列,我都需要使用子选择。
解决方案
推荐阅读
- javascript - 托管在 GitHub 上的 React 路由器页面在刷新时中断
- r - 使用R获取列表中前五个连续日期的第一个日期
- asynchronous - 如何让 CUDA 在内核启动后返回控制权?
- node.js - 您如何可靠地从服务器提供图像?
- javascript - 在 typeorm 中使用存储库时我们如何保存关系
- angular - 错误错误:致命:对不起,太多的客户已经 ApolloError 在角度
- c# - Automapper 仅在映射对象列表时覆盖不在源中的目标值
- python - 如何绘制测量矩阵
- universal-binary - 如何在 qbs 中安装通用二进制工件?
- swift - 如何将带有'&'的字典参数传递给Swift中的Objective-C方法