0
我有一個存儲主機消息的表,我試圖按類型對消息進行分組,並顯示它們發生的分鐘數。我需要顯示每個組的最短消息日期和最大消息日期。我有以下查詢,並且我可以按照最短時間和消息時間的類型獲取消息,但是我需要最短時間爲上一行的最大時間。按消息類型分組,每個消息組之間的持續時間以分鐘爲單位
;WITH cte as (
SELECT CRS, WindowNumber, StateOfServiceReason, DateOfEntry,
ROW_NUMBER() OVER(PARTITION BY StateOfServiceReason ORDER BY CRS, Windownumber, DateOfEntry) AS gn,
ROW_NUMBER() OVER (ORDER BY CRS, WindowNumber, DateOfEntry) AS rn
FROM [dbo].[ServiceLog]
WHERE 1 = 1
AND CRS = 'BBP'
AND WindowNumber = 1), cte2 AS (
SELECT CRS, WindowNumber, StateOfServiceReason, DateOfEntry, gn, rn, gn - rn as gb
FROM cte) , cte3 AS (
SELECT CRS, WindowNumber,StateOfServiceReason, MIN(DateOfEntry) AS MinMsgDate, MAX(DateOfEntry) As MaxMsgDate,
DATEDIFF(MINUTE, MIN(DateOfEntry), Max(DateOfEntry)) as TotalMinutes
FROM cte2
GROUP BY CRS, WindowNumber,StateOfServiceReason, gb)
我的輸出是這樣的:
CRS WindowNumber StateOfServiceReason MinMsgDate MaxMsgDate TotalMinutes
BBP 1 Unknown 2017-07-01 00:07:46 2017-07-01 02:47:05 160
BBP 1 OperatorMaintenance 2017-07-01 02:47:05 2017-07-01 03:01:10 0
BBP 1 Unknown 2017-07-01 03:01:10 2017-07-01 08:37:26 336
BBP 1 OperatorMaintenance 2017-07-01 08:37:26 2017-07-01 18:36:14 598
我想它喜歡這個
CRS WindowNumber StateOfServiceReason MinMsgDate MaxMsgDate TotalMinutes
BBP 1 Unknown 01/07/2017 00:07:46 01/07/2017 02:47:06 xx
BBP 1 OperatorMaintenance 01/07/2017 02:47:06 01/07/2017 03:01:10 xx
BBP 1 Unknown 01/07/2017 03:01:10 01/07/2017 08:37:27 xx
BBP 1 OperatorMaintenance 01/07/2017 08:37:27 01/07/2017 18:36:14 xx
我已經與查詢玩弄了一會兒現在和任何幫助將不勝感激。
我通過寫作'WITH cte AS'來接受這是sqlserver嗎?什麼版本? –
SQL Server 2014 –