我有一个包含一些随机自然数的表,例如:
number
-------
2
3
1
我想从此表中检索一个集合,其中每行将包含与值显示的次数相同的次数,例如上面它将是:
number
-------
2
2
3
3
3
1
我正在考虑这样的查询:
select t.number from table t, (select level from dual connect by level <= t.number)
但显然它不起作用。
如何解决?
答案 0 :(得分:2)
这是对Oracle数据库的查询:
SELECT t1.number
FROM t t1
JOIN (SELECT LEVEL FROM dual CONNECT BY LEVEL<=(SELECT MAX(number) FROM t)) t2
ON t2.level<= t1.number;
答案 1 :(得分:1)
尝试这种方式:
select t.id
from tab t
join (SELECT ROWNUM as id
FROM ALL_OBJECTS
WHERE ROWNUM<=(select max(id) from tab)) t2 on t2.id <= t.id;
我不确定此查询的性能如何,但结果与预期一致。
<强> Sql fiddle Demo 强>
答案 2 :(得分:1)
这是MS-SQL:
declare @str nvarchar(max);
set @str = 'select * from table where number = 0 ';
declare @c2 int;
declare @c3 int;
with cte as (select row_number() over (order by number) as seq,number from table)
select @c2 = max(seq) from cte;
declare @c1 int = 1;
declare @c4 int = 1;
select @c3 = min(number) from table
while (@c1 <= @c2)
begin
while (@c4 <= @c3)
begin
set @str += ' union all select * from table where number = ' + cast (@c3 as nvarchar)
set @c4 += 1
end
set @c1 += 1;
select @c3 = number from table where number = @c3 + 1
set @c4 = 1
end
set @str += ' order by number'
execute(@str)