2016-02-14 53 views
2

我有一張如下所述的數據表。將類似的多行合併爲一個

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

檢查了這一點:HTTP: //stackoverflow.com/questions/194852/concat enate-many-rows-into-a-single-text-string 您需要先修剪'Time'字段的日期 – Nicarus

回答

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 ║ 
╚══════╩══════╩══════════╩════════════════════════════╝ 
+0

這是SQL Server的正確答案。不幸的是,它是這個冗長的/複雜的,而許多其他DBMS的做得更好,並且具有簡單的功能。 – Nicarus