2011-08-03 168 views
5

無法在Oracle PIVOT子句中使用用戶定義的聚合函數。Oracle PIVOT子句中的用戶定義聚合函數

我創建了一個名爲string_agg的用戶定義聚合函數。
我能夠在一個簡單的語句,如使用它...

select id, string_agg(value) from 
(
    select 'user1' as id, 'BMW' as value, 'CAR'  as type from dual union 
    select 'user1' as id, 'Audi' as value, 'CAR'  as type from dual union 
    select 'user2' as id, 'Honda' as value, 'CAR'  as type from dual union 
    select 'user1' as id, 'Dell' as value, 'COMPUTER' as type from dual union 
    select 'user1' as id, 'Sony' as value, 'COMPUTER' as type from dual union 
    select 'user2' as id, 'HP' as value, 'COMPUTER' as type from dual 
) 
group by id, type

結果:
ID TYPE STRING_AGG(VALUE) 
user1  CAR    Audi,BMW 
user1  COMPUTER  Dell,Sony 
user2  CAR    Honda 
user2  COMPUTER  HP 

然而,當我嘗試使用相同的功能樞軸條款
select * from 
( 
    select id, type, string_agg(value) as value from 
    (
     select 'user1' as id, 'BMW' as value, 'CAR'  as type from dual union 
     select 'user1' as id, 'Audi' as value, 'CAR'  as type from dual union 
     select 'user2' as id, 'Honda' as value, 'CAR'  as type from dual union 
     select 'user1' as id, 'Dell' as value, 'COMPUTER' as type from dual union 
     select 'user1' as id, 'Sony' as value, 'COMPUTER' as type from dual union 
     select 'user2' as id, 'HP' as value, 'COMPUTER' as type from dual 
    ) 
    group by id, type 
) 
PIVOT (string_agg(value) FOR id IN ('user1' user1, 'user2' user2));

我得到以下錯誤...
ORA-56902: expect aggregate function inside pivot operation

預期結果是...

TYPE USER1 USER2 
COMPUTER Dell,Sony HP  
CAR   Audi,BMW Honda
+0

「select table,string_agg(value)from table1」將給出一個ORA-00937錯誤,因爲您沒有group by子句。你可以給我們一個完整的例子,一些與樞軸和你的聚合功能的SQL失敗。 – Gerrat

+0

感謝您的反饋。編輯原始帖子以提供詳細示例 – nick

+0

看起來您正在使用此處的string_agg函數:http://www.oracle-base.com/articles/misc/StringAggregationTechniques.php。我找不到任何失敗原因。也許一個bug(也許樞軸不適用於用戶定義的聚合函數)?如果您將第二次出現的string_agg更改爲「max」,它會給出您想要的結果,但 – Gerrat

回答

0

支點不必是在同一集合函數:

關於嘗試wmsys.wm_concat,而不是你的用戶定義的聚合
select * from 
( 
    select id, type, LISTAGG(value) WITHIN GROUP (ORDER BY 1) as value from 
    (
     select 'user1' as id, 'BMW' as value, 'CAR'  as type from dual union 
     select 'user1' as id, 'Audi' as value, 'CAR'  as type from dual union 
     select 'user2' as id, 'Honda' as value, 'CAR'  as type from dual union 
     select 'user1' as id, 'Dell' as value, 'COMPUTER' as type from dual union 
     select 'user1' as id, 'Sony' as value, 'COMPUTER' as type from dual union 
     select 'user2' as id, 'HP' as value, 'COMPUTER' as type from dual 
    ) 
    group by id, type 
) 
PIVOT (max(value) FOR id IN ('user1' user1, 'user2' user2)); 
+0

這不會產生與他自定義的string_agg函數相同的輸出(但是,如果將包含LISTAGG的行更改回OP所具有的行,它仍然可以工作並生成所需的輸出)。 – Gerrat

+0

是的。我也想到了這一點。只是想知道爲什麼我不能在PIVOT中使用用戶定義的agg函數。 – nick

0

什麼?

+0

我應該澄清...演示非常簡單 - 我所追求的是一個函數,我可以傳遞一個數字或一個字符串,並確定它是否應該計算總和或concat – nick