我有一个表,其中两个字段是id,controlflag。它看起来像
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;
它给出了结果,但是第二次和第三次出现(不是第一次)被复制了一个no。时间。 它看起来像
id Flag
123 6,12,12,12,12,17,17,17,17,17.
有人知道这里有什么问题吗?
答案 0 :(得分: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