有一张表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;
执行结果: