以下是Oracle 10g
以后的变体。因为原始数据集中有大量行,所以我会尽量避免涉及在完整结果集之上进行分组和分析函数的解决方案。
此示例的基表:
create table tab1 (
ID number,
col1 varchar2(4),
col2 varchar2(4),
col3 varchar2(4),
col4 varchar2(4)
)
首先,收集每个ID
排序集合的所有列:
select
tab1.ID,
cast( multiset(
select
decode(level,
1, tab1.col1,
2, tab1.col2,
3, tab1.col3,
4, tab1.col4,
null
)
from dual
connect by level <= 4
order by
decode(level,
1, tab1.col1,
2, tab1.col2,
3, tab1.col3,
4, tab1.col4,
null
)
nulls last
) as sys.ODCIVarchar2List) sorted_values
from tab1;
拥有这样一个数据集,可以在保持指定顺序的同时将值解码回列:
select
ID,
(
select column_value
from table(data_list.sorted_values)
where rownum = 1
) as col1,
(
select max(decode(rownum, 2, column_value, null))
from table(data_list.sorted_values)
) as col2,
(
select max(decode(rownum, 3, column_value, null))
from table(data_list.sorted_values)
) as col3,
(
select max(decode(rownum, 4, column_value, null))
from table(data_list.sorted_values)
) as col4
from (
select
rownum, -- this needed as workaround for Oracle bug
tab1.ID,
cast( multiset(
select
decode(level,
1, tab1.col1,
2, tab1.col2,
3, tab1.col3,
4, tab1.col4,
null
)
from dual
connect by level <= 4
order by
decode(level,
1, tab1.col1,
2, tab1.col2,
3, tab1.col3,
4, tab1.col4,
null
)
nulls last
) as sys.ODCIVarchar2List) sorted_values
from tab1
)
data_list
SQLFiddle test
请注意,rownum
必须存在于内部select
子句中作为此 Oracle 错误的解决方法。