开发避坑指南(31):Oracle 11g LISTAGG函数使用陷阱,缺失WITHIN子句解决方案

错误信息

java 复制代码
Error querying database. Cause: java.sql.SQLSyntaxErrorException: ORA-02000: 缺失 WITHIN 关键字

查询语句

使用LISTAGG函数将多行数据合并为单行字符串,如下:

sql 复制代码
select
    t.order_no as orderNo,
    t.account_no,
    (select listagg(a.bank_name,',')  from t_account_info a 
        where t.account_no = a.account_no and a.account_type = '01') as bankName,
    t.payer_name as payername
from t_order_info t
where 1=1
and t.order_no is not null;

错误分析

报以上错误的问题是oracle的版本和listagg的关键字使用不对应,当前用的是oracle 11g ,该版本的listagg使用需要在后面加上within group(order by 字段),如果是oracle 19c的话可以直接使用listagg(字段,',')。

解决办法

将查询语句修改为如下:

sql 复制代码
select
		t.order_no as orderNo,
		t.account_no,
		(select listagg(a.bank_name,',') within group (order by a.bank_name) from t_account_info a 
			where t.account_no = a.account_no and a.account_type = '01') as bankName,
		t.payer_name as payername
		
from t_order_info t
where 1=1
and t.order_no is not null;
相关推荐
踏月的造梦星球6 小时前
达梦数据库执行计划与性能分析入门:EXPLAIN、AUTOTRACE 与 ET
服务器·数据库·oracle
尽兴-10 小时前
企业数据库选型与演进:Oracle、达梦、MySQL 与分库分表实践
数据库·mysql·oracle·分库分表
一个儒雅随和的男子14 小时前
多租户方案的选型
数据库·oracle
龙仔7252 天前
人大金仓KingbaseES V8 手动单库备份&恢复操作笔记
数据库·笔记·oracle·人大金仓
️学习的小王2 天前
MySQL 实战:从建表到索引管理的完整指南
数据库·mysql·oracle
乖巧的妹子3 天前
SQL知识点
数据库·sql·oracle
Zww08913 天前
erp系统常见优化点
数据库·oracle
—Miss. Z—4 天前
计算机二级MySQL——基本操作题
数据库·mysql·oracle
G.O.G.O.G4 天前
《LeetCode SQL 从入门到进阶(MySQL)》06(下)
数据库·sql·oracle
名字还没想好☜4 天前
用 pytest fixture 组织可维护的测试:告别一堆重复的 setUp
数据库·python·oracle·pytest·测试