gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:52:51 24 4
gpt4 key购买 nike

无法在 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

结果是:
<b>ID          TYPE            STRING_AGG(VALUE)</b>
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<br/>

预期 结果是...

<b>TYPE        USER1       USER2</b>
COMPUTER Dell,Sony HP
CAR Audi,BMW Honda

最佳答案

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

关于database - Oracle PIVOT 子句中的用户定义聚合函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6933066/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com