在逗号分隔列表中转换结果
Turning results in comma separated list
我使用这段代码得到以下结果:
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
对于每个重复的“Prod number”,我想获得一个逗号分隔的重复文档 # 列表。
使用 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
我使用这段代码得到以下结果:
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
对于每个重复的“Prod number”,我想获得一个逗号分隔的重复文档 # 列表。
使用 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