Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeating rows based on column value in each row

Tags:

sql

oracle

I've this table with the following data



Job  Quantity   Status  Repeat 
1    100         OK     2 
2    400         HOLD   0 
3    200         HOLD   1 
4    450         OK     3 

Based on the value in the Repeat column for each row, the row should be repeated again. For example for the Job 1, Repeat value is 2 so the Job 1 should repeat two more times.

The resultant table should be as below



Job      Quantity   Status  Repeat 
1        100        OK      2 
1        100        OK      2 
1        100        OK      2 
2        400        HOLD    0 
3        200        HOLD    1 
3        200        HOLD    1 
4        450        OK      3 
4        450        OK      3 
4        450        OK      3 
4        450        OK      3 

Can someone please help me out with this query? am using oracle 10g

like image 213
user991255 Avatar asked Jun 26 '12 05:06

user991255


People also ask

How do you repeat rows a specified number of times based on another column in Excel?

In the popping dialog, choose Copy and insert rows option in the Type section, then choose the range that you want to repeat to Insert Range textbox, and choose the column that decides the repeat times to the Repeat Times textbox. Click Ok. Then the rows will be repeated by the selected column.

How do you repeat a column in SQL?

To create a column with repeated data, set the mode of the column to REPEATED in the schema. A repeated field can be accessed as an ARRAY type in Google Standard SQL. A RECORD column can have REPEATED mode, which is represented as an array of STRUCT types.


2 Answers

You could use a recursive CTE:

with    cte(Job, Repeat, i) as 
        (
        select  Job
        ,       Repeat
        ,       0
        from    YourTable
        union all
        select  Job
        ,       Repeat
        ,       i + 1
        from    cte
        where   cte.i < cte.Repeat
        )
select  *
from    cte
order by
        Job
,       i

Live example at SQL Fiddle.

like image 198
Andomar Avatar answered Sep 24 '22 11:09

Andomar


Supposing you won't generate more than 1000 rows per row:

with num as (select level as rnk from dual connect by level<=1000)
select Job,  Quantity,   Status,  Repeat, rnk 
from t join num on ( num.rnk <= repeat )
order by job, rnk;

Here is a test: http://sqlfiddle.com/#!4/4519f/12

UPDATE: As Jeffrey Kemp said, you can "detect" the maximum with a subquery:

with num as (select level as rnk 
             from dual 
             connect by level<=(select max(repeat) from t)
             )
select job,  quantity,   status,  repeat, rnk 
from t join num on ( num.rnk <= repeat )
order by job, rnk;
like image 30
Florin stands with Ukraine Avatar answered Sep 23 '22 11:09

Florin stands with Ukraine