1. 程式人生 > >sqlServer 多行合並為一行

sqlServer 多行合並為一行

group by 分享 情況 mage server subject where for test

 通過 FOR xml path(‘‘) 合並字符串記錄
-- 分組合並字符串記錄(針對情況 一個id對於多個條記錄,要求合並一行)
SELECT
    name,
    Subject = (
               STUFF(
                    (SELECT ‘,‘ + Subject
                     FROM test
                     WHERE name = A.name
                     FOR xml path(‘‘)
                    ),1,1,‘‘
                    )
                 )
FROM test A
GROUP by name
效果如下:

技術分享圖片

sqlServer 多行合並為一行