0

I have following table

NAME    quantity
a           5
b           3
c           2

I need write some oracle sql (only) query which will output following:

NAME    quantity
a           1
a           1
a           1
a           1
a           1
b           1
b           1
b           1
c           1
c           1
SQLChao
  • 7,709
  • 1
  • 17
  • 32
  • So you want to break apart the quantities into values of 1 for every single name? – Michael Platt Nov 01 '17 at 16:30
  • Yes, you are understood correct! – Arzu Isakova Nov 01 '17 at 16:31
  • So generally this is a really weird thing to do. What is the purpose of this query? Is it just to print stuff in the console? If you are passing the data back to an application, the logic to separate each of the names would be in the application. So could you elaborate a bit more about the reason you want to do this? – Michael Platt Nov 01 '17 at 16:33
  • It's just self testing test! – Arzu Isakova Nov 01 '17 at 16:34
  • I don't quite understand "self testing test." If you are just printing you can use some cursor logic probably to loop over the rows. – Michael Platt Nov 01 '17 at 16:35
  • I know, there is other solutions which can be done easily using pl/sql. I also can write some function which will pipe rows over loop or table, but I need solution in pure sql! – Arzu Isakova Nov 01 '17 at 16:37
  • @Michael Platt - there are in deed use cases where this query (even is sound weird) is required. Some interfaces / tools can't cope with aggregated data and you must go back to detail level. – Marmite Bomber Nov 01 '17 at 16:41

2 Answers2

1
with  
row_num as (select rownum i from dual connect by level <= (select max(quantity) quantity from tab))
select NAME, QUANTITY from tab join row_num on row_num.i <= tab.quantity
order by 1

The CTO query provides the grid (rows 1 to max quantity). Use it to join to your table constraining the quantity.

Marmite Bomber
  • 19,886
  • 4
  • 26
  • 53
0

Well, I'm not an Oracle guy, but I found that question interesting. I'm rather in PostgreSQL. If you know an Oracle's equivalent of PostgreSQL's generate_series function, the solution could look like this:

SELECT
    X.name,
    1
FROM (
    SELECT
        T.name,
        generate_series(1, T.quantity)
    FROM
        unnest(ARRAY[('a'::char, 5), ('b'::char, 3), ('c'::char, 2)]) AS T(name char(1), quantity integer)
) AS X;

The unnest part is just to emulate the original data table.

Maybe this could help you find an answer.

Adam
  • 5,403
  • 6
  • 31
  • 38