T-SQL MS SQL资料如何通过分组将行合并为单行

问题描述

我有一个SQL查询

SELECT [B].[Id],[B].[CreateDate],[Author],[B].[WorkcenterId],[B].[AreaId],[B].[SubAreaId],[B].[Description],[PriorityId],[BreakdownStatusEnum],[ApproveDate],[StartDate],[FinishedDate],[BreakdownStartCheckListId],[ApprovedBy],[BreakdownReason],[D].[Name] AS ResponsibleDepartment
  FROM [Breakdowns_Kohl].[dbo].[Breakdowns] AS [B]
  INNER JOIN Workcenters AS [WC] ON B.WorkcenterId = WC.Id
  INNER JOIN SubAreas AS [S] ON B.SubAreaId = S.Id
  INNER JOIN Areas AS [A] ON B.AreaId = A.ID
  LEFT JOIN Relation_Department_Workcenter AS REL_DW ON B.WorkcenterId = REL_DW.WorkcenterId
  LEFT JOIN Department AS [D] ON REL_DW.DepartmentId = D.Id

返回表:

enter image description here

我无法弄清楚如何将其放在最后一列并以逗号分隔的单行中,如下所示:

enter image description here

解决方法

要将最后一列聚合为一个逗号分隔的字符串,称为ResponsibleDepartment,类似这样

SELECT [B].[Id],[B].[CreateDate],[Author],[B].[WorkcenterId],[B].[AreaId],[B].[SubAreaId],[B].[Description],[PriorityId],[BreakdownStatusEnum],[ApproveDate],[StartDate],[FinishedDate],[BreakdownStartCheckListId],[ApprovedBy],[BreakdownReason],string_agg([D].[Name],',') within group (order by [B].id) ResponsibleDepartment
  FROM [Breakdowns_Kohl].[dbo].[Breakdowns] AS [B]
  INNER JOIN Workcenters AS [WC] ON B.WorkcenterId = WC.Id
  INNER JOIN SubAreas AS [S] ON B.SubAreaId = S.Id
  INNER JOIN Areas AS [A] ON B.AreaId = A.ID
  LEFT JOIN Relation_Department_Workcenter AS REL_DW ON B.WorkcenterId = REL_DW.WorkcenterId
  LEFT JOIN Department AS [D] ON REL_DW.DepartmentId = D.Id

group by [B].[Id],[BreakdownReason]
,

如果您使用的是上面提到的SQL Server 2017或更高版本,则可以轻松使用String_AGG聚合函数,否则,可以像下面的问题一样使用填充函数和xml:

string_agg for sql server pre 2017