将多行结果合并为一行

时间:2018-02-20 12:18:04

标签: sql oracle listagg

我想使用XMLAGG函数将多个结果合并在一行中 这是我正在使用的

RTRIM(XMLAGG(XMLELEMENT(E,B.TEAM_NAME,',').EXTRACT('//text()') ORDER BY 
B.TEAM_NAME ).GetClobVal(),',') MY_TEAM_NAMES, 
RTRIM(XMLAGG(XMLELEMENT(E,A.TEAM_NAME,',').EXTRACT('//text()') ORDER BY 
A.TEAM_NAME).GetClobVal(),',') YOUR_TEAM_NAMES

我希望获得独特的结果,并将它们组合在一行中。 目前我的结果如下: -

MY_TEAM_NAMES                 
Klaus Directs,Klaus Directs,Klaus Directs,Klaus team,Klaus team,Night Riders,Night Riders

YOUR_TEAM_NAMES
Beckham Team,Louise Golf Team,Louise Golf Team,Louise Golf Team,Louise Peers,Louise Peers,Louise Peers

但我想从MY_TEAM_NAMES和YOUR_TEAM_NAMES中删除重复的值。

在from子句中使用distinct关键字有一种解决方案,在这种情况下无法使用。这些结果最初是以下列格式出现的关系:

MY_TEAM_NAMES   YOUR_TEAM_NAMES 
Klaus Directs   Louise Peers
Night Riders    Louise Peers
Klaus Directs   Beckham Team
Klaus Directs   Louise Golf Team
Klaus team      Louise Peers
Klaus team      Louise Golf Team
Night Riders    Louise Golf Team

1 个答案:

答案 0 :(得分:0)

您可以在主要查询之前尝试使用distinct,例如:

with tmpT as 
(
select 'Klaus Directs' as MY_TEAM_NAMES, 'Louise Peers' as YOUR_TEAM_NAMES from dual
union all select 'Night Riders', 'Louise Peers' from dual
union all select 'Klaus Directs', 'Beckham Team' from dual
union all select 'Klaus Directs', 'Louise Golf Team' from dual
union all select 'Klaus team', 'Louise Peers' from dual
union all select 'Klaus team', 'Louise Golf Team' from dual
union all select 'Night Riders', 'Louise Golf Team' from dual
)
select listagg(decode(typeR,1,TEAM_NAMES,null),', ') within group (order by TEAM_NAMES) as MY_TEAM_NAMES 
     , listagg(decode(typeR,2,TEAM_NAMES,null),', ') within group (order by TEAM_NAMES) as YOUR_TEAM_NAMES
  from (select distinct MY_TEAM_NAMES as TEAM_NAMES, 1 as typeR from tmpT
        union select distinct YOUR_TEAM_NAMES, 2 from tmpT
       )