sql - 将数据库中的多列合并为一列?
问题描述
我编写了以下 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 查询的输出 -
解决方案
在 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;
推荐阅读
- mysql - Mysql 通过乘以 id 过滤
- c# - 如果我有具有非只读结构作为成员的 ac# 只读结构,编译器将使用 in 参数创建防御性副本
- flutter - 错误:没有名为“列表”的命名参数
- css - Flexdashboard 导航栏颜色
- reactjs - 重定向使用
来自反应路由器 - python - 如何解析 JSON 并确定值是集合还是嵌套集合?
- python - Django 自定义表单动态原始 ID
- reactjs - 在本机反应中使用抽屉导航登录和注销
- php - Linux 将 PHP 7.4 添加到 Webmin/Virtualmin
- c++ - 编译 DLL(CURL 库)的问题(Visual Studio)