我有下表
TABLE A
| S | D |
----------
| 1 | 01 |
| 2 | 01 |
| 2 | 03 |
我希望我的查询结果采用以下格式
| S | D |
|1,2| 01 |
| 2 | 03 |
如何在SQL中获取此内容
答案 0 :(得分:2)
在STUFF
的帮助下,我们可以实现此目标
declare @temp table
(
S int,
D nvarchar(10)
)
insert into @temp values (1,'01')
insert into @temp values (2,'01')
insert into @temp values (2,'03');
SELECT D,
STUFF(
(SELECT ',' + CAST(S AS VARCHAR(10))
FROM @temp
WHERE D = a.D
FOR XML PATH (''))
, 1, 1, '') AS Remark
FROM @temp AS a
GROUP BY D