2015-09-07 55 views
1

我有表和數據,如下面,數據轉置使用Oracle SQL查詢

Create table transpose (a number, b number, c number); 

insert into transpose values (1,4,7); 
insert into transpose values (2,5,8); 
insert into transpose values (3,6,9); 
commit; 
select * from transpose; 

A B C 
1 4 7 
2 5 8 
3 6 9 

問:我需要下面的輸出使用SQL查詢,這是possbile到 retrive數據(移調數據)?

A B C 
    1 2 3 
    4 5 6 
    7 8 9 

請幫忙解決這個問題。

+0

你的表* *轉沒有秩序。沒有秩序的轉置操作是否有意義? – Codo

+0

在Oracle文檔 –

+0

@WW中查找「數據透視表」。好點子;我更新瞭解決方案。我假設在擺動之前,表格必須以鍵值格式轉換。 –

回答

0

有兩件重要的事情要考慮。

1)一個SQL表沒有含義順序,所以你必須添加order信息來唯一定義轉置表的列。 (我在表中添加了一個列ID來模擬它)。

2)如果你正在尋找一個固定的數列和行的解決方案,你可以在SQL查詢代碼的結果見下文(對於一個動態的解決方案我不建議使用SQL)

select 
    (select a from transpose where id = 1) a, 
    (select a from transpose where id = 2) b, 
    (select a from transpose where id = 3) c 
from dual 
union all 
select 
    (select b from transpose where id = 1) a, 
    (select b from transpose where id = 2) b, 
    (select b from transpose where id = 3) c 
from dual 
union all 
select 
    (select c from transpose where id = 1) a, 
    (select c from transpose where id = 2) b, 
    (select c from transpose where id = 3) c 
from dual; 

 A   B   C 
---------- ---------- ---------- 
    1   2   3 
    4   5   6 
    7   8   9 

更新 - 解決方案與PIVOT

與樞提出@WW這裏解決

with trans as (
/* add one select for each column */ 
select id, 'A' col_name, a col_value from transpose union all 
select id, 'B' col, b col_value from transpose union all 
select id, 'C' col, b col_value from transpose) 
select * from trans 
PIVOT (sum(col_value) col_value 
for (id) in 
(1 as "C1", /* add one entry for each row (ID) */ 
2 as "C2", 
3 as "C3") 
) 
+0

感謝您的信息。 –