【问题标题】:How to concat rows separated by a space in oracle?如何在oracle中连接由空格分隔的行?
【发布时间】:2019-08-23 15:58:02
【问题描述】:
我正在尝试将表中的行合并/合并为一行。我尝试使用 listagg,但由于 varchar 限制,这不起作用。
create table tmp(word VARCHAR2(4000),
lvl NUMBER);
insert into tmp2 values('python',1);
insert into tmp2 values('java',2);
select listagg(word,' ') within group(order by lvl) as listagg_output from tmp;
输出应该类似于 python java。
【问题讨论】:
标签:
oracle
oracle11g
whitespace
concat
listagg
【解决方案1】:
这么长的字符串你会怎么做?
不管怎样,看看这个例子;如果listagg 不起作用,xmlagg 会。
SQL> create table test (id, col) as
2 select rownum, a.column_name
3 from user_tab_columns a cross join user_tab_columns b
4 cross join user_tab_columns c;
Table created.
SQL> select count(*) from test;
COUNT(*)
----------
9261
SQL> select listagg(col, ' ') within group (order by null) result from test;
select listagg(col, ' ') within group (order by null) result from test
*
ERROR at line 1:
ORA-01489: result of string concatenation is too long
SQL> select length(xmlagg(xmlelement(e, col, ' ').extract('//text()') order by null).GetClobVal()) length_result
2 from test;
LENGTH_RESULT
-------------
51156
SQL>
【解决方案2】:
你的问题很简单:
您创建了表tmp
您将测试数据插入到表tmp2
您对tmp 的查询没有返回任何结果,因为tmp 中没有数据
解决方法是将你的测试数据插入tmp:
create table tmp(word VARCHAR2(4000),
lvl NUMBER);
insert into tmp values('python',1);
insert into tmp values('java',2);
select listagg(word,' ') within group(order by lvl) as listagg_output from tmp;
现在返回 python java
dbfiddle here