根据类型结果连接列值

时间:2018-11-28 11:40:16

标签: sql sql-server tsql

  Declare @name nvarchar(max),@Id int
  SELECT @Id=[EmpType],@name =ISNULL(@name + ',','')+[UserName] FROM [dbo].[TestTable]
  Group by [EmpType]
  SELECT @Id,@name

此代码出错,如何获取结果员工类型明智的串联用户名

Expecting Result set

1 个答案:

答案 0 :(得分:0)

您可以在下面使用STUFF()函数

SELECT [EmpType],  abc = STUFF(
             (SELECT ',' + [UserName]
              FROM [dbo].TestTable] t1
              WHERE t1.[EmpType] = t2.[EmpType]
              FOR XML PATH (''))
             , 1, 1, '') from [dbo].TestTable] t2
group by [EmpType];