2016-12-05 36 views
0

如果給定以下有序數據集(1分鐘間隔),我將如何使用Microsoft SQL Server創建新記錄集,該記錄集將給定項目的所有單個代碼相加並呈現總結如下所示?我在想,我應該能夠在分區上使用某種聚合函數,但我不知道從哪裏開始。使用SQL Server添加行以生成摘要

請注意DateTimedatetime而其餘列的類型是varchar。我正在使用SQL Server 2012 Express。

輸入數據:

DateTime    Item  Code Description 
2016-12-02 16:34:00 0   1  Some Description 
2016-12-02 16:35:00 0   1  Some Description 
2016-12-02 16:36:00 0   1  Some Description 
2016-12-02 16:37:00 0   1  Some Description 
2016-12-02 16:38:00 0   1  Some Description 
2016-12-02 16:39:00 0   1  Some Description 
2016-12-02 16:40:00 0   2  Some Description 
2016-12-02 16:41:00 0   2  Some Description 
2016-12-02 16:42:00 0   2  Some Description 
2016-12-02 16:43:00 0   4  Some Description 
2016-12-02 16:44:00 0   4  Some Description 
2016-12-02 16:45:00 0   4  Some Description 
2016-12-02 16:46:00 0   4  Some Description 
2016-12-02 16:47:00 0   4  Some Description 
2016-12-02 16:48:00 1   1  Some Description 
2016-12-02 16:49:00 1   2  Some Description 
2016-12-02 16:50:00 1   2  Some Description 
2016-12-02 16:51:00 1   2  Some Description 
2016-12-02 16:52:00 1   2  Some Description 
2016-12-02 16:53:00 1   3  Some Description 
2016-12-02 16:54:00 0   1  Some Description 
2016-12-02 16:55:00 0   1  Some Description 
2016-12-02 16:56:00 0   1  Some Description 
2016-12-02 16:57:00 0   8  Some Description 
2016-12-02 16:58:00 0   8  Some Description 
2016-12-02 16:59:00 0   8  Some Description 
2016-12-02 17:00:00 0   6  Some Description 
2016-12-02 17:01:00 0   6  Some Description 

預期輸出數據(開始日期應的代碼和結束日期的第一次出現的日期時間應的代碼的最後出現):

Start DT    End DT    Item  Code Description 
2016-12-02 16:34:00 2016-12-02 16:39:00 0   1  Some Description 
2016-12-02 16:40:00 2016-12-02 16:42:00 0   2  Some Description 
2016-12-02 16:43:00 2016-12-02 16:47:00 0   4  Some Description 
2016-12-02 16:48:00 2016-12-02 16:49:00 1   1  Some Description 
2016-12-02 16:50:00 2016-12-02 16:52:00 1   2  Some Description 
2016-12-02 16:53:00 2016-12-02 16:53:00 1   3  Some Description 
2016-12-02 16:54:00 2016-12-02 16:56:00 0   1  Some Description 
2016-12-02 16:57:00 2016-12-02 16:59:00 0   8  Some Description 
2016-12-02 17:00:00 2016-12-02 17:01:00 0   6  Some Description 
+2

這將是巨大的,如果你能在樣本數據提供一些真正的日期。 –

+1

Appologies費利克斯,我應該包括協助測試等我已經包括日期現在。 – beliskna

回答

2

你想要的是將連續日期的島嶼分組。 Here是傑夫MODEN寫了一篇文章,提供了一個解決這個問題:

WITH Cte AS(
    SELECT *, 
     rn = DATEADD(MINUTE, - ROW_NUMBER() OVER(PARTITION BY Item, Code ORDER BY DateTime), Datetime) 
    FROM Data 
) 
SELECT 
    StartDate = MIN(DateTime), 
    EndDate  = MAX(DateTime), 
    Item, 
    Code, 
    Description = MAX(Description) 
FROM Cte 
GROUP BY 
    Item, Code, rn 
ORDER BY 
    StartDate, EndDate; 

ONLINE DEMO

+0

感謝輸入菲利克斯,我會檢查出來! – beliskna