Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return multiple identical rows based on a quantity field in the row itself?

I'm using oracle to output line items in from a shopping app. Each item has a quantity field that may be greater than 1 and if it is, I'd like to return that row N times.

Here's what I'm talking about for a table

product_id, quanity
1, 3,
2, 5

And I'm looking a query that would return

1,3
1,3
1,3
2,5
2,5
2,5
2,5
2,5

Is this possible? I saw this answer for SQL Server 2005 and I'm looking for almost the exact thing in oracle. Building a dedicated numbers table is unfortunately not an option.

like image 324
user126715 Avatar asked Sep 08 '10 05:09

user126715


1 Answers

I've used 15 as a maximum for the example, but you should set it to 9999 or whatever the maximum quantity you will support.

create table t (product_id number, quantity number);
insert into t values (1,3);
insert into t values (2,5);

select t.* 
  from t 
    join (select rownum rn from dual connect by level < 15) a 
                                 on a.rn <= t.quantity
order by 1;
like image 122
Gary Myers Avatar answered Oct 24 '22 20:10

Gary Myers