将列结果转换为oracle中的多行

时间:2019-04-24 06:54:47

标签: sql oracle split delimiter

我在Oracle数据库中有material_info

MATERIAL    COUNTRIES
----------------------------
HX345TY     US,IN,SG,CN,JP
MXT15WO     SL,AU,IN,US,AF
UIY7890#RT  UK,US,IN,SG,PK

我希望输出如下

MATERIAL    COUNTRIES
-----------------------------
HX345TY     US
HX345TY     IN
HX345TY     SG
HX345TY     CN
HX345TY     JP
MXT15WO     SL
MXT15WO     AU
MXT15WO     IN
MXT15WO     US
MXT15WO     AF
UIY7890#RT  UK
UIY7890#RT  US
UIY7890#RT  IN
UIY7890#RT  SG
UIY7890#RT  PK

我为此编写了查询,如下所示。但它不起作用。谁能给出解决方案

select material, trim(regexp_substr(COUNTRIES,'[^,]+', 1, level) ) COUNTRIES, level
from material_info connect by regexp_substr(COUNTRIES, '[^,]+', 1, level) is not null;

2 个答案:

答案 0 :(得分:2)

您应该更喜欢prior + sys_guid技术。对于大量的记录,它的效率远比完全有效。

select material,
       regexp_substr(countries, '[^,]+', 1, level) countries
  from material_info
connect by level <= regexp_count(countries, '[^,]+')
and prior material = material
and prior sys_guid() is not null;

DEMO

答案 1 :(得分:0)

您可以通过使用distinctregexp_count来进行动态更改

select distinct material,
       regexp_substr(countries, '[^,]+', 1, level) countries
  from material_info
connect by level <= regexp_count(countries, '[^,]+')
order by material;

或使用group by material, countries, level作为

select material,
       regexp_substr(countries, '[^,]+', 1, level) countries
  from material_info
connect by level <= regexp_count(countries, '[^,]+')
group by material, countries, level;

甚至无需使用trim

Demo