如何将多行中的字段合并到分隔列表中?

How do I combine a field from multiple rows into a delimited list?

我有一个 table 有很多(30+)列和大约 250k 行。我想获取三列(GroupId、名称和物种),按 GroupId 对它们进行分组,然后将多行的物种字段合并为一列。

例如以下数据:

1     NameA     Cat
2     NameA     Dog
3     NameA     BigBird
4     NameB     Chicken
6     NameC     Wolf
7     NameC     Lion

期望的结果:

1     NameA     Cat,Dog,BigBird
2     NameB     Chicken
3     NameC     Wolf,Lion

这 SQL 将数据分组在一起:

SELECT GROUPID, NAME, SPECIES,
ROW_NUMBER() OVER (partition by GROUPID order by SPECIES) r
from TableName;

如何合并每个组的 Species 字段并创建一个包含逗号分隔列表的字段?

您可以使用 listagg() 自 Oracle 11g:

select NAME
     , listagg(SPECIES, ', ') within group (order by GROUPID) as "SPECIES"
from TableName
group by NAME

如果您只需要唯一值:

select NAME
     , listagg(SPECIES, ', ') within group (order by GROUPID) as "SPECIES"
from (
   select distinct NAME
        , SPECIES
   from TableName
) t
group by NAME

wm_concat():

select NAME
     , wm_concat(distinct SPECIES) as "SPECIES"
from TableName
group by NAME

SQL 更喜欢这个查询:

select 
    row_number() over(order by name) as group_id, name,
    stuff( (select ',' + species  
            from tbl_species s1
            where tbl_species.name = s1.name
            for xml path('') ), 1, 1, '') as species
 from 
     tbl_species 
 group by 
     name

https://sqlwhisper.wordpress.com/2013/03/24/stuff-and-for-xml-path-for-string-concatenation/

您可以参考此站点以了解更多关于 stufffor xml path