PostgreSQL中如何实现键值反向映射:拆分聚合列并重组数据
PostgreSQL 拆分逗号分隔列并聚合对应字段
原始数据
| name | pets |
|---|---|
| bob | cat, dog |
| steve | cat, parrot |
| dave | dog |
目标结果
| pet | names |
|---|---|
| dog | bob, dave |
| cat | bob, steve |
| parrot | steve |
实现SQL语句
SELECT TRIM(pet) AS pet, STRING_AGG(name, ', ') AS names FROM your_table, UNNEST(STRING_TO_ARRAY(pets, ',')) AS pet GROUP BY TRIM(pet) ORDER BY pet;
语句说明
STRING_TO_ARRAY(pets, ','):把pets列的逗号分隔字符串转换成数组格式。UNNEST(...) AS pet:将数组展开为独立行,让每个name对应单个pet记录。TRIM(pet):清理pet字符串前后的空格(适配原始数据里逗号后带空格的情况)。STRING_AGG(name, ', '):按pet分组后,把对应name用逗号加空格拼接成字符串。GROUP BY TRIM(pet):以清理后的pet值作为分组依据。ORDER BY pet:按pet名称排序,和目标结果顺序匹配。
内容的提问来源于stack exchange,提问作者SoftwareThings
相关产品推荐
相关产品推荐

