2

我有一个表,其中两个字段是 id,controlflag.It 看起来像

Id    CntrlFlag       
121   SSSSSRNNNSSRSSNNR
122   SSSNNRRSSNNRSSSSS           
123   RRSSSNNSSSSSSSSSSSSSSS

我必须以下列形式获得输出(R的出现)

Id    Flag
121   6,12,17
122   6,7,12
123   1,2

我尝试了 oracle 查询(我从这个论坛获得):

select  mtr_id,listagg(str,',') within group (order by lvl) as flags from
 ( select  mtr_id, instr(mtr_ctrl_flags,'R', 1, level) as str, level as lvl             
    from mer_trans_reject           
    connect by level <= regexp_count(mtr_ctrl_flags, 'R'))group by mtr_id;

它给出了结果,但第 2 次和第 3 次出现(不是第一次)被重复了。次。看起来像

id   Flag
123 6,12,12,12,12,17,17,17,17,17.

有人能知道这里有什么问题吗?

4

1 回答 1

0

可以通过选择不同的关键字来避免。还有其他方法吗?

是的,有,但这个有点重(不同会花费你更少):

with t1(Id1, CntrlFlag) as(
  select 121, 'SSSSSRNNNSSRSSNNR'      from dual union all
  select 122, 'SSSNNRRSSNNRSSSSS'      from dual union all
  select 123, 'RRSSSNNSSSSSSSSSSSSSSS' from dual
)
select w.id1
     , listagg(w.r_pos, ',') within group(order by w.id1) as R_Positions
  from (select q.id1 
             , regexp_instr(q.CntrlFlag,'R', 1, t.rn) as r_pos
          from t1 q
         cross join (select rownum rn
                       from(select max (regexp_count(CntrlFlag, 'R')) ml
                              from t1
                            )
                           connect by level <= ml      
                      ) t
         ) w  
where w.r_pos > 0                          
group by w.id1

结果:

 ID1        R_POSITIONS
----------  -----------
       121  12,17,6
       122  12,6,7
       123  1,2
于 2013-07-31T13:02:12.827 回答