SFMC中使用GROUP_CONCAT带SEPARATOR报错,求字段合并解决方法
SFMC 实现字段分组合并的正确SQL写法
问题背景
现有数据表:
item item_id components chair 1001 wood chair 1001 screw chair 1001 paint book 1002 pages book 1002 bind
需要按item和item_id分组,将components用逗号合并成预期结果:
item item_id components chair 1001 wood,screw,paint book 1002 pages,bind
原使用MySQL风格的GROUP_CONCAT语句在SFMC中报错:Error saving the Query field.Incorrect syntax near 'SEPARATOR',原语句:
SELECT item_id, GROUP_CONCAT(components SEPARATOR ',') FROM table GROUP BY item_id
解决方案
SFMC基于类SQL Server语法,不支持GROUP_CONCAT,可采用以下两种方法:
方法1:使用STRING_AGG(推荐,SFMC新版本支持)
SELECT item, item_id, STRING_AGG(components, ',') AS components FROM your_table_name GROUP BY item, item_id
注意:必须同时按item和item_id分组,避免丢失item字段,保证结果和预期一致。
方法2:FOR XML PATH兼容写法(适配低版本)
如果你的SFMC版本不支持STRING_AGG,用XML拼接实现:
SELECT DISTINCT t.item, t.item_id, STUFF( ( SELECT ',' + components FROM your_table_name WHERE item = t.item AND item_id = t.item_id FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)'), 1, 1, '' ) AS components FROM your_table_name t
FOR XML PATH('')将同组的components拼接成带逗号前缀的字符串,STUFF函数用于移除开头多余的逗号。
内容的提问来源于stack exchange,提问作者user u
相关产品推荐
相关产品推荐

