从一行中选择多个值

时间:2011-06-16 09:26:12

标签: oracle oracle11g

我有一张看起来像这样的表

A 1,2 
B 3,4,5

我想生成一个如下所示的结果集:

A 1 
A 2 
B 3 
B 4
B 5

是否有SQL语句可以执行此操作?我正在使用Oracle。

1 个答案:

答案 0 :(得分:1)

create table foo (
  var1 varchar2(1),
  var2 varchar2(15)
);
insert into foo (var1, var2) values ('A', '1,2');
insert into foo (var1, var2) values ('B', '3,4,5');
insert into foo (var1, var2) values ('C', '6');

-- This will work if you are using oracle 11g
-- otherwise you will need to *guess* at the max number of rows
select var1, var2
  from (
      select var1
           , substr(var2
                    , instr(var2, ',', 1, l.appearance)+1
                    , instr(var2, ',', 1, l.appearance+1) - instr(var2, ',', 1, l.appearance)-1) var2
        from (select var1, ','||var2||',' var2 from foo)
           , (select level appearance 
                from dual
          connect by level - 1 <= (select max(regexp_count(var2, ',')) from foo)) l
        ) 
    where var2 is not null
order by var1, var2;

-- This will work if you are using oracle 10g
select var1, var2
  from (
      select var1
           , substr(var2
                    , instr(var2, ',', 1, l.appearance)+1
                    , instr(var2, ',', 1, l.appearance+1) - instr(var2, ',', 1, l.appearance)-1) var2
        from (select var1, ','||var2||',' var2 from foo)
           , (select level appearance 
                from dual
          connect by level - 1 <= 99) l
        ) 
    where var2 is not null
order by var1, var2;