我有一个包含许多(30+)列和~250k行的表。我想取三个列(GroupId,Name和Species),按GroupId对它们进行分组,并将多行的Species字段连接成一个。
例如,以下数据:
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字段并使用以逗号分隔的列表创建字段?
答案 0 :(得分:2)
自Oracle 11g起,您可以使用listagg()
:
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
答案 1 :(得分:1)
对于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/
您可以参考此网站,详细了解stuff
和for xml path