我有一个表,其中我有一个列REC_ORDER,其中有 20 次出现,如 REC_ORDER_1,REC_ORDER_2 到 REC_ORDER_20.规范化器转换后,我得到一个输出列作为REC_ORDER。我想知道如何将此规范化器转换转换为 SQL 查询。
您可以使用SELECT
的UNPIVOT
子句,如下所示:
create table demo(id number, n1 number, n2 number, n3 number, n4 number, n5 number);
insert into demo values (1, 45, 87, 96, 33, 17);
insert into demo values (2, 245, 287, 296, 233, 217);
commit;
select * from demo
unpivot (
val
for num in (
n1 as '1',
n2 as '2',
n3 as '3',
n4 as '4',
n5 as '5'
)
);
结果集如下所示:
| ID | NUM | VAL |
|----|-----|-----|
| 1 | 1 | 45 |
| 1 | 2 | 87 |
| 1 | 3 | 96 |
| 1 | 4 | 33 |
| 1 | 5 | 17 |
| 2 | 1 | 245 |
| 2 | 2 | 287 |
| 2 | 3 | 296 |
| 2 | 4 | 233 |
| 2 | 5 | 217 |
在 http://sqlfiddle.com/#!4/bf9cb/8/0 中看到它
你可以像这样创建 SQL -
SELECT occurance1.id as id, occurance1.value1 from source_table occurance1
union all
SELECT occurance2.id as id, occurance2.value2 from source_table occurance2
union all
SELECT occurance3.id as id, occurance3.value3 from source_table occurance3
union all
...
SELECT occurance20.id as id, occurance20.value20 from source_table occurance20`