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

时间:2015-09-08 10:28:22

标签: sql tsql sql-server-2005 relational-database

我需要一个脚本,它将PLAN_ID连接到下表中冒号分隔的字符串中的Reason值,并将它们放在另一个表中,保持为Order值。如何实现这一目标?

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

1 个答案:

答案 0 :(得分:2)

下面的内容应该有效:

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语句的输出插入到所需的表中。