0

我有一个 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

返回表: 在此处输入图像描述

我无法弄清楚如何将它放入最后一列并用逗号分隔的单行中,例如:

在此处输入图像描述

4

2 回答 2

1

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

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],
      [B].[CreateDate]
      ,[Author]
      ,[B].[WorkcenterId]
      ,[B].[AreaId]
      ,[B].[SubAreaId]
      ,[B].[Description]
      ,[PriorityId]
      ,[BreakdownStatusEnum]
      ,[ApproveDate]
      ,[StartDate]
      ,[FinishedDate]
      ,[BreakdownStartCheckListId]
      ,[ApprovedBy]
      ,[BreakdownReason]
于 2020-09-28T14:13:59.453 回答
0

如果您使用的是 SQL Server 2017 或更高版本,您可以轻松地使用 String_AGG 聚合函数,如果不是,您可以使用 stuff 函数和 xml,就像在这个问题中一样:

sql server pre 2017 的 string_agg

于 2020-09-28T15:59:09.717 回答