2014-03-06 87 views
0

我有一個表,如下所示:的Oracle SQL樞翻譯

SNF     SFCM  POOL   QUOTA 
a     US   eng   11 
a     US   sud   20 
b     UK   aau   30 

不過想顯示它,如下所示:

SNF  SFCM  eng  sud  aau 
a  US   11  20   
b  UK       30 

我已經試過如下

使用樞軸
SELECT a.* FROM test 
PIVOT 
(
SUM(QUOTA) AS QUOTA 
FOR pool 
IN ('eng', 'sud', 'aau') 
) 

但似乎無法得到正確的輸出。

任何人都可以建議我嗎?另外,我想知道是否可以使用SQL語句而不是'eng', 'sud', 'aau'。所以IN(select POOL from test)

謝謝。

回答

0

您的查詢應該如下:

SELECT SNF, SFCM, eng_quota, sud_quota, aau_quota FROM nc_so1 
PIVOT 
(
SUM(QUOTA) AS QUOTA 
FOR pool 
IN ('eng' as eng, 'sud' as sud, 'aau' as aau) 
) 

此外,它不可能使用SQL AFAIK

+0

它是PL/SQL,但您可以將EXEC IMMEDIATE用於動態SQL。 –

+1

@RobertCo此答案中沒有PL/SQL代碼。你想說啥? –

0

你最初的SQL得到期望的結果(輕微改變)生成一個動態清單:

SQL> with t (SNF, SFCM, POOL, QUOTA) as 
    2 (
    3 select 'a','US','eng',11 from dual union all 
    4 select 'a','US','sud',20 from dual union all 
    5 select 'b','UK','aau',30 from dual 
    6 ) 
    7 SELECT * FROM t 
    8 PIVOT 
    9 (
10 SUM(QUOTA) 
11 FOR (pool) 
12 IN ('eng' "ENG", 'sud' "SUD", 'aau' "AAU") 
13 ) 
14/

SNF SFCM  ENG  SUD  AAU          
--- ---- ---------- ---------- ----------          
a US   11   20             
b UK         30 

PS至於動態數據透視表 - 僅限於可用的XML表單:

SQL> with t (SNF, SFCM, POOL, QUOTA) as 
    2 (
    3 select 'a','US','eng',11 from dual union all 
    4 select 'a','US','sud',20 from dual union all 
    5 select 'b','UK','aau',30 from dual 
    6 ) 
    7 SELECT * FROM t 
    8 PIVOT XML 
    9 (
10 SUM(QUOTA) 
11 FOR (pool) 
12 IN (select pool from t) 
13 ) 
14/

SNF SFCM POOL_XML                
--- ---- --------------------------------------------------      
a US <PivotSet><item><column name = "POOL">aau</column>      
     <column name = "SUM(QUOTA)"></column></item><item>      
     <column name = "POOL">eng</column><column name = "      
     SUM(QUOTA)">11</column></item><item><column name =      
      "POOL">sud</column><column name = "SUM(QUOTA)">20      
     </column></item></PivotSet>            

b UK <PivotSet><item><column name = "POOL">aau</column>      
     <column name = "SUM(QUOTA)">30</column></item><ite      
     m><column name = "POOL">eng</column><column name =      
      "SUM(QUOTA)"></column></item><item><column name =      
      "POOL">sud</column><column name = "SUM(QUOTA)"></      
     column></item></PivotSet>