首页 > 解决方案 > 将数据库中的多列合并为一列?

问题描述

我编写了以下 SQL 查询:

SELECT DISTINCT i.IncidentReference Reference, s.Name Site, it.Description IncidentTypes
    , i.Description, FORMAT(i.CreatedOn,'d MMM yyyy', 'en-US' ) Logged 
FROM Incident i 
INNER JOIN TEST_USWM_TestAutomation.TEST_USWM.uvw_AvailaibleSites s ON i.SiteId = s.Id 
JOIN IncidentIncidentType iit ON i.Id = iit.IncidentId 
JOIN IncidentType it ON iit.IncidentTypeId = it.Id 
JOIN IncidentStatus ins ON i.IncidentStatusId = ins.Id 
WHERE s.Id = 1 /*:siteId */
AND ins.Name = 'Logged' 
AND i.CreatedOn BETWEEN DATEADD(DAY, -30, GETUTCDATE()) AND GETUTCDATE()

它返回以下结果:

Reference  Site  IncidentTypes                 Description    Logged
7032       0110  Refrigeration Outage          njfdgdf        25 Sep 2019
7095       0110  Fire/False Evacuation         testing        2 Oct 2019
7096       0110  Fire/False Evacuation         testing        2 Oct 2019
7097       0110  Fire/False Evacuation         test           2 Oct 2019
7097       0110  Flood                         test           2 Oct 2019
7097       0110  Gas Leak/Suspected Gas Leak   test           2 Oct 2019
7098       0110  Flood                         testing        2 Oct 2019
7168       0110  Fire/False Evacuation         test           7 Oct 2019
7330       0110  Refrigeration Outage          Test           15 Oct 2019

但是,我希望将具有相同引用的所有行合并为一行。例如,对于 Reference - 7097,我希望看到列 IncidentTypes 的样子 - Gas Leak/Suspected Gas Leak, Fire/False Evacuation, Flood

最好的方法是什么?

编辑:我已经尝试了@GMB 在下面发布的查询,但我收到错误 -函数 'STRING_AGG' 可能没有 WITHIN GROUP 子句。这似乎是我正在使用的 SQL Server 版本的问题。有没有其他方法可以在不升级版本的情况下解决这个问题?

编辑: @Gordon Linoff 查询的输出 -

标签: sqlsql-server

解决方案


在 MySql 中,您可以使用 group_concat(it.Description) 然后按参考分组

SELECT DISTINCT i.IncidentReference Reference, s.Name Site, group_concat(it.Description) IncidentTypes, 
i.Description, FORMAT(i.CreatedOn,'d MMM yyyy', 'en-US' ) Logged 
FROM Incident i 
INNER JOIN TEST_USWM_TestAutomation.TEST_USWM.uvw_AvailaibleSites s ON i.SiteId = s.Id 
JOIN IncidentIncidentType iit ON i.Id = iit.IncidentId 
JOIN IncidentType it ON iit.IncidentTypeId = it.Id 
JOIN IncidentStatus ins ON i.IncidentStatusId = ins.Id 
WHERE s.Id = 1 /*:siteId */
AND ins.Name = 'Logged' 
AND i.CreatedOn BETWEEN DATEADD(DAY, -30, GETUTCDATE()) AND GETUTCDATE() Group by reference;

推荐阅读