2014-09-05 93 views
1

我在這個網站上看到很多例子,但我還沒有得到任何解決方案。所以iam發佈了這個問題。
請建議我如何解決此問題。 Iam在oracle上工作11gR1版本將列轉換爲oracle中的行11gR1

year   price  Quantity 
1991   10  50 
2008   20  96 

我想輸出

1991 10 
1991 20 
2008 50 
2008 96 

我試圖與旋轉功能,但沒有實現和獲得異常的SQL命令沒有正確結束。下面是
是我的查詢。 Iam不擅長SQL。

select * from (select year, price ,quanty from my_table) 
     pivot(min(year) year in (price, quanty)); 

編輯了以上問題:

select year, value 
from my_table 
unpivot 
(
    value 
    for col in (price, quantity) 
) u 

對於上述查詢,如果我有產品的名稱名稱多了一個列是VARCHAR,IAM讓我在通過列上方查詢如下。

select year, value 
    from my_table 
    unpivot 
    (
     value 
     for col in (price, quantity,productname) 
    ) u 

得到錯誤的

ORA-01790:表達式必須具有相同的數據類型對應的表達

請@BlueFeet表明這一點。

+0

的ORA-01790錯誤是不言自明的錯誤,你不這麼認爲嗎? – zaratustra 2014-09-05 12:22:20

回答

3

看起來您需要UNPIVOT而不是數據透視表。 unpivot是將多行轉換爲多列的過程。

由於使用的是Oracle 11g中,你可以使用逆透視功能:

select year, value 
from my_table 
unpivot 
(
    value 
    for col in (price, quantity) 
) u 

SQL Fiddle with Demo

你也可以使用UNION ALL這樣寫:

select year, price as value 
from my_table 
union all 
select year, quantity as value 
from my_table 

SQL Fiddle with Demo

基於這樣的事實,你也想在最後的結果varchar列,你需要轉換所有列是相同的數據類型 - 你可以在一個子查詢做到這一點:

select year, value 
from 
(
    select year, 
    to_char(price) as price, 
    to_char(quantity) as quantity, 
    productname 
    from my_table 
) 
unpivot 
(
    value 
    for col in (price, quantity, productname) 
) u; 

SQL Fiddle with Demo

1

試試這個:

with t(year, price, Quantity) as(
    select 1991, 10, 50 from dual union all 
    select 2008, 20, 96 from dual 
) 
select year, new_col1 
    from t 
unpivot (
    new_col1 for new_col in (price, quantity)) 

YEAR NEW_COL1 
---------------- 
1991 10 
1991 50 
2008 20 
2008 96 

更多here