如何根据一列选择行数

时间:2019-10-04 00:34:28

标签: sql oracle row-number

所以我在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,但不确定其工作原理吗?

5 个答案:

答案 0 :(得分:1)

您需要递归查询才能实现。

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

输出:

enter image description here

请参见sqlfiddle

答案 1 :(得分:1)

您可以按以下方式使用connect:

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>

干杯!

答案 2 :(得分:1)

这将起作用:

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

检查小提琴:http://sqlfiddle.com/#!4/14a67/1

谢谢!

答案 3 :(得分: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>

答案 4 :(得分:1)

您可以使用包含connect by level <= some_number的{​​{1}}逻辑来链接表cross join

tab

Demo