Sql Oracle 11g:LISTAGG忽略空值

Sql Oracle 11g:LISTAGG忽略空值,sql,plsql,oracle11g,Sql,Plsql,Oracle11g,我有一些表表1,其中包含数据: +------------+ | COL1 | +------------+ | FOO | | BAR | | (null) | | EXP | +------------+ () 当我执行时: SELECT listagg(col1, '#') within group(ORDER BY rownum) FROM table1 我收到:FOO#BAR#EXP但我想要:FOO#BAR#EXP

我有一些表
表1
,其中包含数据:

+------------+
|    COL1    |
+------------+
|   FOO      |
|   BAR      |
|  (null)    |
|   EXP      |
+------------+
()

当我执行时:

SELECT listagg(col1, '#') within group(ORDER BY rownum) 
  FROM table1
我收到:
FOO#BAR#EXP
但我想要:
FOO#BAR#EXP

LISTAGG
忽略空单元格:/)

不编写自己的函数就可以实现这一点吗?

试试这个

select 
  REPLACE(listagg(NVL(col1,' '), '#') within group(order by rownum),'# #','##') 
from table1

尝试以下方法:

select replace(
                listagg(coalesce(col1,'replace'), '#') 
                within group(order by rownum),      
       'replace','') 
from table1
Sql Fiddle

您可以使用
NVL(col1,#')
在这里您可以传递任何值而不是null

请尝试:

select replace(listagg(nvl(col1, '#') , '#') 
       within group(order by rownum), '##', '#') 
from table1
另一种方法是使用


在每个值之前预先添加分隔符(这将生成仅用于空值的分隔符),然后聚合而不使用分隔符,并去除前导分隔符。

值得一提的是,使用
listag
,您可能会遇到结果值上4000个字符的限制,然后寻求其他解决方案。解决方案是
xmlagg
,相比之下,它尊重
null
值。因此,考虑使用基于占位符的技巧是否使用代码> ListaGG值得。


(我的情况正好相反:我需要忽略完全符合
listag
的空值,但后来我达到了极限,被迫学习使用
xmlagg
子句忽略值。这可以使用
nvl2
函数,但那是另一回事。)

@WBAR当两个连续的列为空时,有关此项的更多信息无效,因为REPLACE将只替换第一个出现的列,并且无法匹配以下列。有什么提示吗?
select replace(listagg(nvl(col1, '#') , '#') 
       within group(order by rownum), '##', '#') 
from table1
SQL> select rtrim(res, '#') as col1
  2    from ( select res
  3                , rn
  4             from table1
  5             model
  6             dimension by (rownum as rn)
  7             measures(cast(null as varchar2(500)) as res, col1)
  8             rules(
  9               res[any] order by rn desc= col1[cv()] || '#' || res[cv() + 1]
 10             )
 11          )
 12   where rn = 1
 13  /

COL1
--------------------
FOO#BAR##EXP
select substr(listagg('#'||col1) within group (order by rownum),2)
from table1