如何根据一列select行数

How to select a number of rows according to a column

所以我在 Oracle 数据库中有两列:

Name / count

我想打印名字 x 次,x 是计数。

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

尝试了 row_number 但不确定它是如何工作的?

你需要递归查询来实现这个。

with cte(nam, ctr) as (
    select 'Paul' as nam, 5 as ctr from dual
    union all
    select 'Sam', 6 as ctr from dual
),
cte2(nam, ct, ctr) as (
    select nam, 1 as ct, ctr from cte
    union all
    select nam, ct + 1, ctr from cte2
    where ct<ctr
)select nam, ct from cte2  
order by nam asc

输出:

sqlfiddle

您可以通过以下方式使用连接:

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>

干杯!!

这会起作用:

select  name
  from  Table1,
        (select  level lvl
           from  dual
           connect by level <= (select max(cnt) from Table1 )
        )
  where lvl <= cnt
  order by name;

检查fiddle:http://sqlfiddle.com/#!4/14a67/1

谢谢!!!

另一个选项(您的查询从第 4 行开始):

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  select name
  5  from your_table cross join table (cast (multiset (select level from dual
  6                                                    connect by level <= count
  7                                                   ) as sys.odcinumberlist));

NAME
----
paul
paul
paul
paul
paul
sam
sam
sam
sam
sam
sam

11 rows selected.

SQL>

您可以使用包含 cross join 到 link 的 connect by level <= some_number 逻辑与您的 table tab :

with tab(Name,"count") as
( select 'Paul', 5 from dual union all select 'Sam', 6 from dual )
 select name, level as seq 
   from dual d
  cross join tab t
connect by level <= t."count"
    and prior name = name
    and prior sys_guid() is not null;

Demo