问题
I am trying to concat/merge rows in a table to one single row. I tried using listagg but due to varchar limitation this doesn't work.
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;
The output should look like python java.
回答1:
What will you do with such a long string?
Anyway, have a look at this example; if listagg
won't work, xmlagg
will.
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:
Your problem is pretty simple:
You created the table
tmp
You inserted your test data into the table
tmp2
Your query against
tmp
returned no results because there was no data intmp
The solution is to insert your test data into 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;
This now returns python java
dbfiddle here
来源:https://stackoverflow.com/questions/57629622/how-to-concat-rows-separated-by-a-space-in-oracle