什么脚本会连接字符串并按列值过滤?

What script would concatenate strings and filter by column value?

我需要一个脚本,它将 PLAN_ID 的 Reason 值连接到以下 table 的冒号分隔字符串中,并将它们放在进一步的 table 中,保持真实订单价值。如何实现?

PLAN_ID Order   Reason
6281    1       Declined
6281    4       Unfit
6281    8       Other
6281    9       Monitoring
6286    1       Declined
6286    5       Unknown Site
6286    10      Not Known

PLAN_ID Reason
6281    Declined;Unfit;Other;Monitoring
6286    Declined;Unknown Site;Not Known

像下面这样的东西应该可以工作:

SELECT  t1.plan_id, 
        STUFF(( SELECT  '; ' + t2.reason 
                FROM    orders AS t2 
                WHERE   t1.plan_id = t2.plan_id
                FOR XML PATH('')
            ), 1, 2, '') as reason
FROM    dbo.orders AS t1 
GROUP BY plan_id

您可以使用简单的 INSERT INTO..SELECT 语法将上述 SELECT 语句的输出插入所需的 table。