如何基于现有SQL查询将同组多值SDG聚合为单行单单元格展示
调整方案
核心逻辑
- 移除原查询中的
DISTINCT,改用分组聚合实现同组数据合并 - 按所有非聚合输出字段(
id、program、Community ID)做分组 - 用对应数据库的字符串聚合函数,将同一组下的
sdg值拼接为逗号分隔的有序字符串,避免顺序混乱
分数据库调整示例
MySQL / MariaDB
SELECT a.id, a.title AS program, b.community_id AS `Community ID`, GROUP_CONCAT(DISTINCT c.goal_id ORDER BY c.goal_id ASC SEPARATOR ',') AS sdg FROM programs_program AS a JOIN associates_programcommunity AS b ON a.id = b.program_id JOIN associates_communitygoal AS c ON b.community_id = c.community_id GROUP BY a.id, a.title, b.community_id
PostgreSQL
SELECT a.id, a.title AS program, b.community_id AS "Community ID", STRING_AGG(DISTINCT c.goal_id::TEXT, ',' ORDER BY c.goal_id ASC) AS sdg FROM programs_program AS a JOIN associates_programcommunity AS b ON a.id = b.program_id JOIN associates_communitygoal AS c ON b.community_id = c.community_id GROUP BY a.id, a.title, b.community_id
SQL Server 2017+
SELECT a.id, a.title AS program, b.community_id AS [Community ID], STRING_AGG(DISTINCT c.goal_id, ',') WITHIN GROUP (ORDER BY c.goal_id ASC) AS sdg FROM programs_program AS a JOIN associates_programcommunity AS b ON a.id = b.program_id JOIN associates_communitygoal AS c ON b.community_id = c.community_id GROUP BY a.id, a.title, b.community_id
注意事项
- 聚合函数中加的
DISTINCT会自动过滤同一组下重复的goal_id,避免输出10,10,11这类冗余值 - MySQL默认对
GROUP_CONCAT结果有最大长度限制(默认1024字节),如果拼接后的字符串过长,可先执行SET SESSION group_concat_max_len = 10240;(数值可按需调整)扩大限制 - 聚合时指定的
ORDER BY保证sdg按升序输出,最终效果为10,11,17而非随机顺序
内容的提问来源于stack exchange,提问作者Kennardy Kusuma
相关产品推荐
相关产品推荐

