简体   繁体   English

Oracle PIVOT子句中的用户定义聚合函数

[英]User-Defined Aggregate functions in Oracle PIVOT clause

Unable to use user-defined aggregate functions in Oracle PIVOT clause. 无法在Oracle PIVOT子句中使用用户定义的聚合函数。

I created a user-defined aggregate function called string_agg. 我创建了一个名为string_agg的用户定义聚合函数。
I am able to use it in a simple statement such as... 我可以在一个简单的声明中使用它,例如......

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

Results in: 结果是:
 ID TYPE STRING_AGG(VALUE) user1 CAR Audi,BMW user1 COMPUTER Dell,Sony user2 CAR Honda user2 COMPUTER HP 

However when I try to use the same function in a pivot clause 但是当我尝试在pivot子句中使用相同的函数时
 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) ); 

I get the following error... 我收到以下错误...
 ORA-56902: expect aggregate function inside pivot operation 

Expected result is... 预期结果是......

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

Pivot doesn't have to be over the same aggregate function: Pivot不必超过相同的聚合函数:

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) );

那么尝试使用wmsys.wm_concat而不是用户定义的聚合呢?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM