在sql中重复每N行的最简单方法

时间:2015-01-14 12:20:40

标签: sql oracle

我知道这可以通过一些复杂的技术,我想知道任何最简单的方法来实现这10个行应该重复的模式。 例如

        select a,b from tablename; (repeating 2 for example)

将给出

        a1,b1     
        a2,b2
        a1,b1  
        a2.b2
        a3,b3
        a4,b4
        a3,b3
        a4,b4

如果它是10,它就像

    a1,b1 to a10,b10 again a1,b1 to a10,b10

然后

    a11,b11 to a20,b20 again a11,b11 to a20,b20

等等

3 个答案:

答案 0 :(得分:2)

使用CTE并联合所有:

with rows as (
      select a, b
      from tablename
      where rownum <= 2
     )
select *
from rows
union all
select *
from rows;

这只是一些警告。如果您想要表中的特定行,则应使用order by。这很重要,因为相同的select可以返回不同的行集。实际上,考虑到这一点,更好的方法可能是:

with rows as (
      select a, b
      from tablename
      where rownum <= 2
     )
select *
from rows cross join
     (select 1 as n from dual union all select 2 from dual) n;

答案 1 :(得分:2)

你想要重复两次十行的块。所以得到:

rows 1 to 10
rows 1 to 10
rows 11 to 20
rows 11 to 20
...

为了获得行n倍交叉连接与包含n个记录的表。 (例如,你可以通过查询一个足够大的表并停在rowcount n来获得。)

您还需要原始记录的行号,因此您可以先获取块1,然后块2,依此类推。使用整数除法从行号到块。

select t.a, t.b
from (select a, b, row_number() over (order by a, b) as rn from tablename) t
cross join (select rownum as repeatno from bigenoughtable where rownum <= 2) r
order by trunc((t.rn -1) / 10), r.repeatno, t.a, t.b;

答案 2 :(得分:1)

我宁愿不要多次使用UNION。我的方式是CONNECT BY ROWNUM <=N。实际上是CARTESIAN JOIN。所以,基本上你需要一个ROW GENERATOR来与它进行笛卡尔联合。

<强>更新

例如,这将重复10行2次 -

SQL> WITH t AS
  2    ( SELECT 'a1' A, 'b1' b FROM dual
  3    UNION ALL
  4    SELECT 'a2' a, 'b2' b FROM dual
  5    UNION ALL
  6    SELECT 'a3' a, 'b3' b FROM dual
  7    UNION ALL
  8    SELECT 'a4' A, 'b4' b FROM dual
  9    UNION ALL
 10    SELECT 'a5' A, 'b5' b FROM dual
 11    UNION ALL
 12    SELECT 'a6' a, 'b6' b FROM dual
 13    UNION ALL
 14    SELECT 'a7' A, 'b7' b FROM dual
 15    UNION ALL
 16    SELECT 'a8' a, 'b8' b FROM dual
 17    UNION ALL
 18    SELECT 'a9' a, 'b9' b FROM dual
 19    UNION ALL
 20    SELECT 'a10' a, 'b10' b FROM dual
 21    )
 22  SELECT A,B FROM t,
 23    (SELECT 1 FROM DUAL CONNECT BY ROWNUM <=2
 24    )
 25    /

A   B
--- ---
a1  b1
a2  b2
a3  b3
a4  b4
a5  b5
a6  b6
a7  b7
a8  b8
a9  b9
a10 b10
a1  b1
a2  b2
a3  b3
a4  b4
a5  b5
a6  b6
a7  b7
a8  b8
a9  b9
a10 b10

20 rows selected.

SQL>

因此,上面CONNECT BY ROWNUM <=10表示重复行10次。如果您希望重复N次,请使用CONNECT BY ROWNUM <=N