我有一张包含数据的表格,如下所述。
Name | Type | Data | Time
DN60 | LTE | CPU Load | 2/14/2016 7:00
DN60 | LTE | CPU Load | 2/14/2016 8:00
DN60 | LTE | CPU Load | 2/14/2016 9:00
我希望最终输出为如下所示的一行。由于日期将始终为当天,因此可以在输出中忽略日期值。
Name | Type | Data | Time
DN60 | LTE | CPU Load | 07:00,08:00,09:00
如何使用简单的SQL语句完成此操作。我正在使用SQL Server 2008。
答案 0 :(得分:3)
以下是使用XML PATH
技巧
;with cte as
(
SELECT *
FROM ( VALUES ('DN60','LTE','CPU Load',Cast('2/14/2016 7:00' AS DATETIME)),
('DN60','LTE','CPU Load',Cast('2/14/2016 8:00' AS DATETIME)),
('DN60','LTE','CPU Load',Cast('2/14/2016 9:00' AS DATETIME)) ) cs (NAME, Type, Data, Time)
)
SELECT DISTINCT a.NAME,
a.Type,
a.Data,
LEFT(cs.time, Len(cs.time) - 1) AS time
FROM cte a
CROSS APPLY (SELECT CONVERT(VARCHAR(20), Time, 8) + ','
FROM cte B
WHERE a.NAME = b.NAME
AND a.Type = b.Type
AND a.Data = b.Data
FOR XML PATH('')) cs (time)
<强>结果:强>
╔══════╦══════╦══════════╦════════════════════════════╗
║ NAME ║ Type ║ Data ║ time ║
╠══════╬══════╬══════════╬════════════════════════════╣
║ DN60 ║ LTE ║ CPU Load ║ 07:00:00,08:00:00,09:00:00 ║
╚══════╩══════╩══════════╩════════════════════════════╝