Oracle 10,11中的Listagg语法

时间:2016-03-24 18:22:50

标签: oracle

希望一切顺利。我有一个简单的程序:

Select 
Soccer||', ' ||football  as test,
ID
From sport
Where ID = 123

以下是上述查询的结果:

Test       ID
Adis, Nike 123
,          123

如何编辑下面的代码以删除逗号“,”以便它只显示一行?

Select
LISTING (a.test, ', ') within group (order by a.test) as equipment,
ID
From
    (
     Select
     soccer||', '||football as test,
     ID
     From test
     where ID =123
    )a
Group by I'd

结果显示

Equipment       ID
, , Adis, Nike  123

我想要的结果:

Equipment  ID
Adis, Nike 123

有人请提供一些反馈吗?我正在运行oracle 11 谢谢!

1 个答案:

答案 0 :(得分:1)

您当前的listagg正在汇总两行'Adis, Nike'', '的现有连续结果,作为列表,并在它们之间添加另一个逗号。连接可能不是你真正想要的;虽然如果只有一个值,你可以跳过逗号:

select soccer
  || case when soccer is not null and football is not null then ', ' end
  || football as test, id
from sport
where id = 123;

TEST                           ID
---------------------- ----------
Adis, Nike                    123
                              123

然后排除外部listagg中的任何空值:

select listagg (equipment, ', ') within group (order by equipment) as equipment, id
from (
  select soccer
    || case when soccer is not null and football is not null then ', ' end
    || football as equipment, id
  from sport
  where id = 123
)
where id = 123
and equipment is not null
group by id;

EQUIPMENT                              ID
------------------------------ ----------
Adis, Nike                            123

您还可以使用union将列转换为单独的行(一种手动的unpivot):

select id, soccer as equipment from sport
union all
select id, football as equipment from sport;

        ID EQUIPMENT                    
---------- ------------------------------
       123 Adis                          
       123                               
       123 Nike                          
       123                               

然后将其用作内联视图,聚合它返回的列表,并排除空条目:

select listagg (equipment, ', ') within group (order by equipment) as equipment, id
from (
  select id, soccer as equipment from sport
  union all
  select id, football as equipment from sport
)
where id = 123
and equipment is not null
group by id;

EQUIPMENT                              ID
------------------------------ ----------
Adis, Nike                            123