How to concat rows separated by a space in oracle?

百般思念 提交于 2021-01-29 13:18:55

问题


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:

  1. You created the table tmp

  2. You inserted your test data into the table tmp2

  3. Your query against tmp returned no results because there was no data in tmp

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!