Oracle重复行N次,其中N是列

时间:2013-12-09 21:24:56

标签: sql oracle oracle10g

我是Oracle新手,我正在尝试做一些不寻常的事情。鉴于此表和数据,我需要选择每一行,并重复DupCount大于1的行。

create table TestTable
(
  Name     VARCHAR(10),
  DupCount NUMBER
)

INSERT INTO TestTable VALUES ('Jane', 1);
INSERT INTO TestTable VALUES ('Mark', 2);
INSERT INTO TestTable VALUES ('Steve', 1);
INSERT INTO TestTable VALUES ('Jeff', 3);

期望的结果:

Name        DupCount
---------   -----------
Jane        1
Mark        2
Mark        2
Steve       1
Jeff        3
Jeff        3
Jeff        3

如果通过单个select语句无法做到这一点,那么我们将非常感谢您对存储过程的任何帮助。

2 个答案:

答案 0 :(得分:7)

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

SQL Fiddle

查询1

WITH levels AS (
  SELECT LEVEL AS lvl
  FROM   DUAL
  CONNECT BY LEVEL <= ( SELECT MAX( DupCount ) FROM TestTable )
)
SELECT Name,
       DupCount
FROM   TestTable
       INNER JOIN
       levels
       ON ( lvl <= DupCount )
ORDER BY Name

<强> Results

|  NAME | DUPCOUNT |
|-------|----------|
|  Jane |        1 |
|  Jeff |        3 |
|  Jeff |        3 |
|  Jeff |        3 |
|  Mark |        2 |
|  Mark |        2 |
| Steve |        1 |

答案 1 :(得分:5)

您可以使用递归cte执行此操作。它看起来像这样

with cte as (name, dupcount, temp)
(
   select name,
          dupcount,
          dupcount as temp
   from testtable
     union all
   select name, 
          dupcount,
          temp-1 as temp
   from cte 
   where temp > 1
)
select name, 
       dupcount
from cte
order by name