根据条件在Oracle中动态重复行

时间:2014-09-16 21:58:38

标签: sql oracle oracle11g connect-by

继承人我拥有的

查询

with temp as (
select 11 as x  from dual
union
select 222 as x  from dual
)
select x from temp t,(SELECT 1
          FROM DUAL 
         CONNECT BY ROWNUM <= 3)

输出

X
--
11
222
11
222
11
222

输出我的愿望

X
--
11
11
222    
222
222

基本上我希望行根据列的长度重复自己&#39; X&#39;值。 所以,如果价值是&#39; abc&#39; 然后该行应重复3次

3 个答案:

答案 0 :(得分:6)

这有效:

with temp as (
select '11' as x  from dual
union
select '222' as x  from dual
)
SELECT x, LEVEL from temp t
        CONNECT BY LEVEL <= LENGTH(t.x) 
and prior x = x
and prior sys_guid() is not null;    

最后一行可以解决问题。使用其他参考PRIOR可以实现相同的目的:

with temp as (
select '11' as x  from dual
union
select '222' as x  from dual
)
SELECT x, LEVEL from temp t
        CONNECT BY LEVEL <= LENGTH(t.x) 
and PRIOR x = x
and PRIOR DBMS_RANDOM.VALUE () IS NOT NULL;    

答案 1 :(得分:2)

由于您使用的是11g,因此可以使用recursive subquery factoring来实现此目的:

with t as (
  select 11 as x  from dual
  union all
  select 222 as x  from dual
),
r (x, idx, len) as (
  select x, 1, length(x)
  from t
  union all
  select r.x, r.idx + 1, r.len
  from r
  where r.idx < r.len
)
select x from r
order by x;

    X
-----
   11
   11
  222    
  222
  222

锚成员获取原始行和值的长度。递归成员向idx添加一个,直到达到长度。

SQL Fiddle

您也可以使用分层查询来执行此操作:

with t as (
  select 11 as x  from dual
  union all
  select 222 as x  from dual
)
select x
from t
connect by level <= length(x)
and prior x = x
and prior sys_guid() is not null;

两个prior子句的组合 - 一个限制重复,另一个涉及非确定性函数,以防止在您这样做时循环 - 为您提供所需的行:

    X
-----
   11
   11
  222    
  222
  222

SQL Fiddle

答案 2 :(得分:-1)

with temp as (
    select 11 as x  from dual
    union
    select 222 as x  from dual
)
select x from temp t,(
    SELECT 1
    FROM DUAL 
    CONNECT BY ROWNUM <= 3)
order by 1