2013-11-01 29 views
1

我有這個結構的表列:SQL樞軸,以返回不同的值作爲列名

|------ ID ------| 
|- 1.20.10.00 -| 
|- 1.20.10.10 -| 
|- 1.20.10.20 -| 
|- 1.20.20.00 -| 
|- 1.20.20.10 -| 
|- 1.40.10.00 -| 
|- 1.40.20.00 -| 
|- 1.60.10.00 -| 
|- 1.60.10.00 -| 

我想運行一個查詢,將轉動根據返回的不同值的數據爲多列一個字符串與值中的左側5個字符一樣,列名稱與like語句中使用的5個字符匹配。讓我給什麼,我想要去一個例子:

|----- 1.20. ----||----- 1.40. ----||----- 1.60. ----| 
|- 1.20.10.00 -||- 1.40.10.00 -||- 1.60.10.00 -| 
|- 1.20.10.10 -||- 1.40.20.00 -||- 1.60.10.00 -| 
|- 1.20.10.20 -| 
|- 1.20.20.00 -| 
|- 1.20.20.10 -| 

我上的Oracle 11g數據庫,所以我想我應該使用PIVOT命令,但我想不出如何設置它增加了DISTINCT和LIKE命令。任何幫助,將不勝感激。

回答

1

爲選項頭號你可以使用row_number() over()解析函數的組合,max()聚合函數和case表達:

select max(case when substr(col, 1, 4) = '1.20' then col end) as "1.20" 
    , max(case when substr(col, 1, 4) = '1.40' then col end) as "1.40" 
    , max(case when substr(col, 1, 4) = '1.60' then col end) as "1.60" 
from (select col 
      , row_number() over(partition by substr(col, 1, 4) 
            order by substr(col, 1, 4)) as rn 
     from t1) 
group by rn 

結果:

1.20  1.40  1.60  
---------- ---------- ---------- 
1.20.10.00 1.40.10.00 1.60.10.00 
1.20.10.10 1.40.20.00 1.60.10.00 
1.20.20.00      
1.20.20.10      
1.20.10.20      

注:這不是一個好列別名的選擇思想。

作爲另一個選項,您可以使用,在Oracle 11g中引入的版本,pivot操作:

select "1.20" 
    , "1.40" 
    , "1.60" 
     from (select col 
        , substr(col, 1, 4) as common_part 
        , row_number() over(partition by substr(col, 1, 4) 
              order by substr(col, 1, 4)) as rn 
       from t1) 
pivot(
    max(col) for common_part in ('1.20' as "1.20" 
           , '1.40' as "1.40" 
           , '1.60' as "1.60") 
) 

結果:

1.20  1.40  1.60  
---------- ---------- ---------- 
1.20.10.00 1.40.10.00 1.60.10.00 
1.20.10.10 1.40.20.00 1.60.10.00 
1.20.20.00      
1.20.20.10      
1.20.10.20      
+0

感謝您的答覆。我喜歡第二種選擇,但是,列中的潛在值可能會改變。我剛剛閱讀Oracle文檔中的pivot命令[link](http://www.oracle.com/technetwork/articles/sql/11g-pivot-097235.html),其中指出「此行[for,in]是必要的,所以不幸的是,你必須事先知道可能的值。這個限制在本文後面描述的查詢的XML格式中得到了放寬。「這似乎限制了我使用pivot命令的能力,而XML不是一個合理的選項。我會繼續努力。謝謝。 – thefreeline