Oracle duplicate row N times where N is a column

眉间皱痕 提交于 2019-12-10 04:28:26

问题


I'm new to Oracle and I'm trying to do something a little unusual. Given this table and data I need to select each row, and duplicate ones where DupCount is greater than 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);

Desired Results:

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

If this isn't possible via a single select statement any help with a stored procedure would be greatly appreciated.


回答1:


You can do it with a hierarchical query:

SQL Fiddle

Query 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 |



回答2:


You can do this with a recursive cte. It would look like this

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


来源:https://stackoverflow.com/questions/20481112/oracle-duplicate-row-n-times-where-n-is-a-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!