我有一个有两列的Oracle DB表。我希望看到每一行重复的次数与第二列中存储的次数相同。该表如下所示:
col1 col2
a 2
b 3
c 1
我想编写一个返回此内容的查询:
col1 col2
a 2
a 2
b 3
b 3
b 3
c 1
因此col2的值决定了行重复的次数。有没有一种简单的方法来实现这一目标?
谢谢!
答案 0 :(得分:3)
Oracle 11g R2架构设置:
CREATE TABLE test ( col1, col2 ) AS
SELECT 'a', 2 FROM DUAL
UNION ALL SELECT 'b', 3 FROM DUAL
UNION ALL SELECT 'c', 1 FROM DUAL
查询1 :
SELECT col1,
col2
FROM test t,
TABLE(
CAST(
MULTISET(
SELECT LEVEL
FROM DUAL
CONNECT BY LEVEL <= t.col2
)
AS SYS.ODCINUMBERLIST
)
)
<强> Results 强>:
| COL1 | COL2 |
|------|------|
| a | 2 |
| a | 2 |
| b | 3 |
| b | 3 |
| b | 3 |
| c | 1 |
答案 1 :(得分:0)
with src (col1, col2) as (
SELECT 'a', 2 FROM DUAL UNION ALL
SELECT 'b', 3 FROM DUAL UNION ALL
SELECT 'c', 1 FROM DUAL
)
SELECT
src.*
FROM
src
JOIN (
SELECT LEVEL val FROM DUAL
CONNECT BY LEVEL <= (SELECT MAX(col2) FROM src)
) gen ON gen.val <= src.COL2
ORDER BY
src.col1
或在Oracle 12中可以使用
with src (col1, col2) as (
SELECT 'a', 2 FROM DUAL UNION ALL
SELECT 'b', 3 FROM DUAL UNION ALL
SELECT 'c', 1 FROM DUAL
)
SELECT
src.*
FROM
src
CROSS APPLY (SELECT NULL FROM DUAL CONNECT BY LEVEL <= src.col2)
ORDER BY
col1;
答案 2 :(得分:0)
这是另一种选择(我添加了一个额外的列只是为了显示其他列可以存在),假设col1是唯一的:
with src (col1, col2, col3) as (
SELECT 'a', 'b', 2 FROM DUAL UNION ALL
SELECT 'b', 'c', 3 FROM DUAL UNION ALL
SELECT 'c', 'd', 1 FROM DUAL
)
select col1, col2, col3
from src
connect by level <= col3
and prior col1 = col1
and prior sys_guid() is not null;
COL1 COL2 COL3
---- ---- ----------
a b 2
a b 2
b c 3
b c 3
b c 3
c d 1
答案 3 :(得分:0)
如果a是你的桌子,那么你也可以这样做:
select a1.col1 , a1.col2
from a a1
join (select level col2 from dual
connect by level < ( select max(col2) + 1 from a)) a2
on a2.col2 between 1 and a1.col2