Search code examples
sqloracle-databaserow-number

How to select a number of rows according to a column


So I have got two columns in an Oracle database:

Name / count

I would like to print the name x times, x being the count.

E.g. Paul / 5 would mean Paul being printed 5 times.
     Sam / 6 would mean Sam being printed 6 times

Tried row_number over but not sure how it works?


Solution

  • You can use connect by as following:

    SQL> WITH YOUR_TABLE AS
      2  (SELECT 'paul' as NAME, 5 AS COUNT FROM DUAL UNION ALL
      3  SELECT 'sam' as NAME, 6 AS COUNT FROM DUAL
      4  ) -- YOUR ACTUAL QUERY STARTS FROM LINE#5
      5  Select t.name, m.lvl
      6  from your_table t
      7  join
      8  (Select level as lvl
      9  from
     10    (Select max(count) as maxcount
     11     from your_table)
     12  Connect by level <= maxcount) m
     13  On (t.count >= m.lvl)
     14  ORDER BY 1,2;
    
    NAME        LVL
    ---- ----------
    paul          1
    paul          2
    paul          3
    paul          4
    paul          5
    sam           1
    sam           2
    sam           3
    sam           4
    sam           5
    sam           6
    
    11 rows selected.
    
    SQL>
    

    Cheers!!