如何根据列的值展开Oracle查询的结果 [英] How to unfold the results of an Oracle query based on the value of a column

查看:41
本文介绍了如何根据列的值展开Oracle查询的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Oracle DB 上有一个包含两列的表.我希望看到每一行重复的次数与存储在第二列中的数字一样多.该表如下所示:

I have a table on a Oracle DB with two columns. I would like to see every row repeated as many times as the number stored in the second column. The table looks like this:

col1 col2  
a    2  
b    3  
c    1

我想写一个返回这个的查询:

I want to write a query that returns this:

col1 col2
a    2  
a    2   
b    3    
b    3    
b    3    
c    1

所以来自 col2 的值决定了一行重复的次数.有没有简单的方法来实现这一目标?

So the value from col2 dictates the number of times a row is repeated. Is there a simple way to achieve this?

谢谢!

推荐答案

SQL Fiddle

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
         )
       )

结果:

| COL1 | COL2 |
|------|------|
|    a |    2 |
|    a |    2 |
|    b |    3 |
|    b |    3 |
|    b |    3 |
|    c |    1 |

这篇关于如何根据列的值展开Oracle查询的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆