将结果转换为逗号分隔列表

时间:2015-01-27 16:31:02

标签: sql list comma

我使用此代码获取以下结果:

Select  [Doc #], 
        [Production Number]
From    vwLiveDocuments
Where   [production number] IN
(
    SELECT  [production number]
    FROM    vwLiveDocuments
    where   [tags] LIKE N'%name of tag%'
    Group by [production number]
    Having Count (*) > 1
)

我会得到以下结果:

'Doc #'     'Production number'
117611      CGI00069441
47864       CGI00069441
47865       CGI00069457
117901      CGI00069457
47866       CGI00069460
117904      CGI00069460
121479      CGI00071490
53934       CGI00071490

您可以在生产编号中看到重复的结果。我想要的是转换此列表以获得以下结果:

'Production number'     'Doc #'
CGI00069441             117611,47864
CGI00069457             47865,117901
CGI00069460             47866,117904
CGI00071490             121479,53934

每个副本的位置"产品编号"我想得到一个逗号分隔的doc#副本列表。

1 个答案:

答案 0 :(得分:2)

使用For xml path()技巧来执行此操作。

;WITH cte
     AS (SELECT [Doc #],
                [Production Number]
         FROM   vwLiveDocuments
         WHERE  [production number] IN (SELECT [production number]
                                        FROM   vwLiveDocuments
                                        WHERE  [tags] LIKE N'%20150126-Appendix B%'
                                        GROUP  BY [production number]
                                        HAVING Count (*) > 1))
SELECT [Production number],
       Stuff((SELECT ',' + CONVERT(VARCHAR(10), [doc #])
              FROM   cte b
              WHERE  b.[Production number] = a.[Production number]
              FOR xml path('')), 1, 1, '') [Doc #]
FROM   cte a
GROUP  BY [Production number]
ORDER  BY [Production Number] ASC