0

I have values like below

1,a,b,c
2,d,e
3,f,g

Expected output

1 a
1 b
1 c
2 d
2 e                 

Can you please help me?

Rajesh123
  • 107
  • 1
  • 5
  • 17
  • 2
    possible duplicate of [Splitting string into multiple rows in Oracle](http://stackoverflow.com/questions/14328621/splitting-string-into-multiple-rows-in-oracle) – Mat May 04 '15 at 08:11
  • Not a pure duplicate though, since it is not just splitting the delimited values into rows, however, repeating the leading substr value in a separate column. Mostly the logic remains same, however, there needs to be an extra rule to eliminate the repeating rows as I explained in my answer. – Lalit Kumar B May 04 '15 at 08:38

1 Answers1

2

It is very much close to implementing the logic to Split comma delimited strings in a table. The only tricky thing is that you have the row number along with the string itself.

You could use ROWNUM as pseudo column, and then filter out those rows where the leading substr of the string is repeating with the ROWNUM.

For example,

Setup

SQL> CREATE TABLE t(text VARCHAR2(4000));

Table created.

SQL>
SQL> INSERT INTO t SELECT '1,a,b,c' text FROM dual;

1 row created.

SQL> INSERT INTO t SELECT '2,d,e' text FROM dual;

1 row created.

SQL> INSERT INTO t SELECT '3,f,g' text FROM dual;

1 row created.

SQL> COMMIT;

Commit complete.

SQL>
SQL> SELECT * FROM t;

TEXT
----------
1,a,b,c
2,d,e
3,f,g

SQL>

Solution:

SQL> WITH DATA AS(
  2  SELECT ROWNUM rn, text FROM t
  3  )
  4  SELECT *
  5  FROM
  6    (SELECT rn,
  7      trim(regexp_substr(t.text, '[^,]+', 1, lines.COLUMN_VALUE)) text
  8    FROM DATA t,
  9      TABLE (CAST (MULTISET
 10      (SELECT LEVEL FROM dual CONNECT BY LEVEL <= regexp_count(t.text, ',')+1
 11      ) AS sys.odciNumberList ) ) lines
 12    )
 13  WHERE TO_CHAR(rn) <> text
 14  ORDER BY rn
 15  /

        RN TEXT
---------- ----------
         1 a
         1 b
         1 c
         2 d
         2 e
         3 f
         3 g

7 rows selected.

SQL>
Lalit Kumar B
  • 47,486
  • 13
  • 97
  • 124
  • Hi,lalit thank you , but it is difficult to understand, is there another option for simple Query – Rajesh123 May 04 '15 at 10:19
  • @Rajesh123 Well, it won't be difficult if you understand REGEXP_SUBSTR, ROW_GENERATOR method. Probably, you need to do some learning and testing. Google around for the keywords I told you. – Lalit Kumar B May 04 '15 at 10:37