How to unfold the results of an Oracle query based on the value of a column(如何根据列的值展开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查询的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何根据列的值展开Oracle查询的结果
基础教程推荐
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- 在多列上分布任意行 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- oracle区分大小写的原因? 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
