SQL分组中的逗号分隔列表

问题描述 投票:0回答:1

我正在尝试在sql中为每个组构建逗号分隔列表,因为使用并行数据仓库我需要在不使用FOR XML或递归函数的情况下执行此操作(不支持)。

任何其他方式来实现这一目标?

Input:  
ID  Value
1   2
1   3
1   4
2   1
2   10

Output: 
ID  List
1   2,3,4
2   1,10
sql string-aggregation parallel-data-warehouse
1个回答
1
投票

这根本不会很好,所以如果你需要性能,我建议你使用其他解决方案(比如SQL Server链接服务器到PDW)。但我相信这应该适用于PDW:

declare @ID int = (select min(ID) from tbl);
declare @Value int = -1;
declare @concat varchar(8000) = '';

create table #tmp (
 ID int,
 [concat] varchar(8000)
)
with (distribution=hash(ID), location=user_db);

while @ID is not null
begin
    set @Value = (select min([Value]) from tbl where ID = @ID and [Value]>@Value);
    if @Value is not null
        set @concat = @concat + case when @concat = '' then '' else ',' end + cast(@Value as varchar(8000));
    else
    begin
        insert #tmp (ID, [concat])
        values (@ID, @concat);

        set @ID = (select min(ID) from tbl where ID > @ID);
        set @Value = -1;
        set @concat = '';
    end
end

select * from #tmp;

drop table #tmp;
© www.soinside.com 2019 - 2024. All rights reserved.