首页 > 解决方案 > 在 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 中,这似乎不可用,这就是为什么我必须使用一个子查询来对区域进行分组,并在外部选择中最终得到预期结果的原因。我想知道是否可以在一次选择中获得此输出。在此示例中,我只有两列,但在实际情况中,我有几列需要以相同的方式进行分组,并且对于每一列,我都需要使用子选择。

标签: sql-serverdistinctstring-agg

解决方案


推荐阅读