2013-12-09 48 views
4

我是Oracle的新手,我试图做一些不寻常的事情。鉴于此表和数据,我需要选择每行,重复的对象,其中DupCount大于1Oracle重复行N次,其中N是列

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语句是不可能的任何有关存储过程的帮助将不胜感激。

+1

什么版本的Oracle?例如,@Hogan递归的CTE示例非常棒,但我相信它至少需要11.2 –

+0

我应该提到它是Oracle 10g。 – Mark

回答

6

您可以使用分层查询做到这一点:

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 | 
+0

完美的作品!谢谢。 – Mark

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 
+0

你需要命名CTE列,否则你会得到一个错误 - 'WITH cte(name,dupcount,temp)AS' [SQLFIDDLE](http://sqlfiddle.com/#!4/2d21b/11) – MT0

+0

这看起来很棒并可能会很好,但我忘了提及我们在10克。谢谢。 – Mark

+0

@ MT0-感谢指针,名称是在SQL Server中推断的。 – Hogan