将逗号分隔的值拆分为多行-Oracle SQL

时间:2019-04-22 19:39:37

标签: sql oracle

我有一张桌子

table1

TEST_TYPE                   H_LEVEL                     HADOOP
22RETGGEDGDD, RRMMNFNEDGDD  Control Directory 1         Interchange Control Header
22RETGGEDGDD, RRMMNFNEDGDD  Control Directory 2         Interchange Control Header
22RETGGEDGDD, RRMMNFNEDGDD  Control Directory 3         Interchange Control Header

我知道如何在列中分隔逗号分隔的值,但在复制所有其他列时,我不知道如何在行中分隔值。

table2

TEST_TYPE           H_LEVEL                     HADOOP
22RETGGEDGDD        Control Directory 1         Interchange Control Header
RRMMNFNEDGDD        Control Directory 1         Interchange Control Header
22RETGGEDGDD        Control Directory 2         Interchange Control Header
RRMMNFNEDGDD        Control Directory 2         Interchange Control Header
22RETGGEDGDD        Control Directory 3         Interchange Control Header
RRMMNFNEDGDD        Control Directory 3         Interchange Control Header

如何在Oracle SQL中做到这一点?

2 个答案:

答案 0 :(得分:1)

这是一个选择;您需要从第6行开始。

SQL> with table1 (test_type, h_level, hadoop) as
  2    (select '22RETGGEDGDD, RRMMNFNEDGDD', 'Control Directory 1', 'Interchange Control Header' from dual
  3     union all
  4     select '22RETGGEDGDD, RRMMNFNEDGDD', 'Control Directory 2', 'Interchange Control Header' from dual
  5    )
  6  select trim(regexp_substr(test_type, '[^,]+', 1, column_value)) test_type,
  7         h_level,
  8         hadoop
  9  from table1 join table(cast(multiset(select level from dual
 10                                       connect by level <= regexp_count(test_type, ',') + 1
 11                                      ) as sys.odcinumberlist )) on 1 = 1
 12  order by 2, 1 desc, 3;

TEST_TYPE            H_LEVEL             HADOOP
-------------------- ------------------- --------------------------
22RETGGEDGDD         Control Directory 1 Interchange Control Header
RRMMNFNEDGDD         Control Directory 1 Interchange Control Header
22RETGGEDGDD         Control Directory 2 Interchange Control Header
RRMMNFNEDGDD         Control Directory 2 Interchange Control Header

SQL>

答案 1 :(得分:0)

您可以使用cross join

with t(test_type, h_level, hadoop) as
(
 select '22RETGGEDGDD, RRMMNFNEDGDD','Control Directory 1','Interchange Control Header' 
   from dual union all
 select '22RETGGEDGDD, RRMMNFNEDGDD','Control Directory 2','Interchange Control Header' 
   from dual union all
 select '22RETGGEDGDD, RRMMNFNEDGDD','Control Directory 3','Interchange Control Header' 
   from dual  
)    
select distinct regexp_substr(test_type,'[^, ]+', 1, level ) as test_type, 
                t2.h_level, t2.hadoop
  from t t1
 cross join ( select h_level, hadoop from t ) t2
 connect by level <= regexp_count(test_type,',' ) + 1
   order by t2.h_level, test_type desc;

Demo