数据库
首页 > 数据库> > oracle group by字符串拼接

oracle group by字符串拼接

作者:互联网

有一张表test,字段分别是主键ID,road_id,user_id,region,现在的需求是对road_id分组,然后将region字段用逗号拼接起来
test表:

分组的SQL如下:

SELECT road_id , LISTAGG(REGION, ',') WITHIN GROUP (ORDER BY road_id) region 
 FROM rasmp_test WHERE region IS NOT NULL GROUP BY road_id

分组后的结果:

发现region有重复的数字,需要对其进行去重
修改后的SQL如下:

SELECT road_id , LISTAGG(REGION, ',') WITHIN GROUP (ORDER BY road_id) region FROM (
	SELECT DISTINCT road_id, region FROM rasmp_test 
) t1 WHERE region IS NOT NULL GROUP BY road_id;

执行结果:

标签:group,region,test,拼接,SELECT,oracle,GROUP,id,road
来源: https://www.cnblogs.com/jorry-yun/p/16350753.html