我在实现连接多行的XML PATH方法时遇到了一些麻烦。因此,如下表所示,测试。
ID Type
1 boy
2 boy
3 boy
1 girl
2 girl
3 man
3 woman
查询是:
SELECT DISTINCT a.ID,
(
SELECT b.Type + ','
FROM Test as b
WHERE a.Type = b.Type
for XML PATH ('')
)
FROM Test as a
但不是返回:
ID Type
1 boy,girl,man,
2 boy,girl,
3 boy,girl,woman
它改为返回:
ID Type
1 boy,boy,boy,
1 girl,girl,
2 boy,boy,boy,
2 girl,girl,
3 boy,boy,boy,
3 man,
3 woman,
发生了什么?
答案 0 :(得分:0)
你加入了错误的领域。
尝试
SELECT DISTINCT a.ID,
(
SELECT b.Type + ','
FROM Test as b
WHERE a.ID = b.ID
for XML PATH ('')
)
FROM Test as a
答案 1 :(得分:0)
而不是使用DISTINCT更喜欢使用GROUP BY
之类的东西......
SELECT a.ID,
STUFF((SELECT ', ' + [Type] [text()]
FROM Test
WHERE ID = a.[ID]
for XML PATH (''),TYPE).
value('.','NVARCHAR(MAX)'),1,2,'') AS [Type]
FROM Test as a
GROUP BY a.ID