我正在尝试使用找到的答案here来连接字符串的分组集合,除了我希望输出在每个项目周围都有引号。
Field A | Field B
1 | A
1 | B
2 | A
1 | "A","B"
2 | "A"
SELECT FieldA , STUFF(( SELECT ','+ FieldB FROM TableName a
WHERE b.FieldA = a.FieldA FOR XML PATH('')),1 ,1, '') Members
FROM TableName b
GROUP BY FieldA;
我尝试在逗号前后添加引号,但格式不正确。
有什么建议吗?
答案 0 :(得分:1)
只需将''''
/ '"'
添加到XML + STUFF方法:
select distinct t1.FieldA,
STUFF((SELECT distinct ',' + ''''+ t2.FieldB + ''''
from yourtable t2
where t1.FieldA = t2.FieldA
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'') data
from yourtable t1;
<强> Rextester Demo 强>
修改强>
或使用QUOTENAME
:
select distinct t1.FieldA,
STUFF((SELECT distinct ',' + QUOTENAME(t2.FieldB, '"')
from yourtable t2
where t1.FieldA = t2.FieldA
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'') data
from yourtable t1;
<强> Rextester Demo2 强>
答案 1 :(得分:1)
我更喜欢第一个建议,但这是一个变体:
SELECT FIELDA, ISNULL([1],'') + ' ' + ISNULL([2], '')
FROM
(SELECT FIELDA, ISNULL(QUOTENAME(FieldB, '"'),'') AS FIELDB
,ROW_NUMBER() OVER (PARTITION BY fielda ORDER BY fielda) AS tbl
FROM yourtable)a
PIVOT (MAX(fieldb) FOR tbl IN ([1],[2])) AS pvt