如何在Oracle 10g中基于逗号分隔值显示逗号分隔的描述?

时间:2013-04-16 17:01:24

标签: oracle oracle10g

我是Oracle技术的新手。早些时候,由于对要求缺乏了解,我发布了同一期的2篇帖子。

表1:

MSGID
-----
1,2,3
2,3
4
null
null

表2:

MID   MSGDESC
----  -------
1     ONE
2     TWO
3     THREE
4     FOUR

预期产出:

XCOL     DESC
-----    -----
1,2,3    ONE,TWO,THREE
2,3      TWO,THREE
4        FOUR

我无法满足此要求。请给我一个解决方案。

注意:表没有任何唯一键或主键值。表1有5000条记录,表2只有80条带描述的记录。

1 个答案:

答案 0 :(得分:0)

create table Table1 (MSGID varchar2(100));

insert into Table1 values ('1,2,3');
insert into Table1 values ('2,3');
insert into Table1 values ('4');
insert into Table1 values (null);
insert into Table1 values (null);

create table Table2 (MID varchar2(100), MSGDESC varchar2(100));

insert into Table2 values ('1','ONE');
insert into Table2 values ('2','TWO');
insert into Table2 values ('3','THREE');
insert into Table2 values ('4','FOUR');

select
  msgid as xcol, 
  "DESC", 
  col1, col2, ..., col12
from
  Table1
  left join (
    select
       msgid,
       wm_concat(msgdesc) as "DESC"
    from
       (
          select
             msgid,
             msgdesc
          from
             (select distinct msgid from Table1 where ...)
             cross join (
                select level as occ from dual connect by level <= 100)
             )
             left join Table2
                on mid = regexp_substr(msgid, '[^,]+', 1, occ)
          where
             occ <= regexp_count(msgid, ',') + 1
          order by msgid, occ
       )
    group by msgid
  ) using (msgid)