如何在Oracle中将分号分隔列转换为行?

时间:2013-12-06 16:29:29

标签: oracle

 Source Table: EMP_LOCATION

 NAME    LOCATION
 -------------------------------
 SMITH     NY;CA;IL;GA
 JAMES     MO;AZ;RI
 FORD      NJ
 SCOTT     TX;VA;WA;NH
 MARTIN    MD;CT

Required Output:

NAME    LOCATION
-------------------
FORD      NJ
JAMES     AZ
JAMES     MO
JAMES     RI
MARTIN    CT
MARTIN    MD
SCOTT     NH
SCOTT     TX
SCOTT     VA
SCOTT     WA
SMITH     CA
SMITH     GA
SMITH     IL
SMITH     NY

1 个答案:

答案 0 :(得分:1)

有些人会要求你展示一些代码,但是当我需要这些时,我花了很多时间创建一个函数,然后我意识到我可以使用connect by来完成它。所以你需要的是:

SELECT name, REGEXP_SUBSTR (location, '[^;]+', 1, LEVEL) AS location
  FROM emp_location
 CONNECT BY 
     LEVEL <= LENGTH(REGEXP_REPLACE (location, '[^;]*')) + 1
  GROUP BY name, REGEXP_SUBSTR (location, '[^;]+', 1, LEVEL)
  ORDER BY name