You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 20:39:05