如何在SQL PDW / Azure SQL DW中连接具有相同ID的许多行

时间:2019-04-23 17:43:13

标签: sql-server azure-sql-database azure-sqldw parallel-data-warehouse

我的表包含两个字段之类的详细信息。我想使用DisplayName来获得唯一的详细信息,例如:我想知道如何使用并行数据仓库/ APS,因为PDW不支持FOR XML PATH功能。

1编辑器,审阅者7 EIC,编辑器,审阅者

  ID      DisplayName
  1        Editor
  1        Reviewer
  7        EIC
  7        Editor
  7        Reviewer
  7        Editor
  19       EIC
  19       Editor
  19       Reviewer

我尝试了以下代码,这些代码可在传统的SQL Server上运行,但APS不支持“用于XML路径”功能。

        SELECT id, displayname = 
     STUFF((SELECT DISTINCT ', ' + displayname
        FROM #t b 
         WHERE b.id = a.id 
      FOR XML PATH('')), 1, 2, '')
      FROM #t a
      GROUP BY id

1 个答案:

答案 0 :(得分:0)

如果您知道要连接的值的数量的固定上限,那么以下方法将起作用。

create table test1 (id integer,email varchar(255)) with (heap,distribution=round_robin);

insert into test1 (id,email) values (1,'abc@msn.com');
insert into test1 (id,email) values (1,'xyz@gmail.com');
insert into test1 (id,email) values (2,'efg@xyz.com');
insert into test1 (id,email) values (2,'efg@xyz.com');

select id as Id,concat_ws(',',[1],[2],[3],[4]) as EmailAddresses from (
    select id,[1],[2],[3],[4]
    from (
        select id,row_number() over (partition by id order by email) seq,email from (
            select distinct id,email from test1
            ) as distinctRows
        ) as numberedRows
    pivot (
        max(email) for seq in ([1],[2],[3],[4])
        ) as pivotLookup
    ) as pivotedRows