开发避坑指南(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;
相关推荐
hljqfl8 分钟前
Oracle存储结构
数据库·oracle
m0_716255002 小时前
批处理一道例题+答案解析+批处理知识点总结 | 批处理高频易错场景 + 正确写法对照表
数据库·oracle
俺不要写代码2 小时前
数据库:DML
数据库·oracle
Irene19913 小时前
Oracle 中:为什么 from 子查询后面需要一个别名
数据库·oracle
杨云龙UP4 小时前
Oracle数据库启动失败:ORA-29701、ORA-01565、ORA-17503故障处理记录_20260429
linux·运维·数据库·oracle·centos
懒铭心4 小时前
Oracle 19c 备份与恢复
oracle
于歌8525 小时前
Oracle批处理操作方法
数据库·oracle
hhb_6186 小时前
VB老旧项目代码重构与性能优化实战方案
oracle·性能优化·重构
whn19776 小时前
虚拟机搭建oracle 19c rac 点滴
数据库·oracle
鸽芷咕8 小时前
KingbaseES数据类型完全指南:从基础CHAR到JSON/XML/几何类型
xml·oracle·json