在SQL中的单行中移动多个行值

时间:2015-08-07 10:33:12

标签: sql sql-server sql-server-2008

我有下表

TABLE A

| S | D  |
----------
| 1 | 01 |    
| 2 | 01 |
| 2 | 03 | 

我希望我的查询结果采用以下格式

| S | D  |
|1,2| 01 |  
| 2 | 03 |

如何在SQL中获取此内容

1 个答案:

答案 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