[英]Grouping rows by message type with duration in minutes between each message group
I have a table that stores messages for a host, I am trying to group the messages by type and show the amount of minutes they occurred for. 我有一个表,用于存储主机的消息,我试图按类型对消息进行分组,并显示发生的分钟数。 I need to show the minimum message date and the maximum message date for each group.
我需要显示每个组的最小消息日期和最大消息日期。 I have the following query and I am able to get the messages to group by type with the min time and message time, however I need the min time to be the max time of the previous row.
我有以下查询,我能够按类型将消息与最小时间和消息时间进行分组,但是我需要将最小时间作为上一行的最大时间。
;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)
My output looks like this: 我的输出如下所示:
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
I would like it to like this 我想要这样
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
I have been playing around with the query for a while now and any help would be appreciated. 我已经玩了一段时间查询,任何帮助将不胜感激。
In sqlserver, the window function LAG(column) OVER(order by x)
can be used to return the value of column in a previous row, where the ORDER BY x
defines what would be the "previous" row. 在sqlserver中,窗口函数
LAG(column) OVER(order by x)
可用于返回上一行的column的值,其中ORDER BY x
定义什么是“上一”行。 Bear in mind you might want to also PARTITION BY your_grouping
to ensure the first row from a group doesn't pull a previous value from another group 请记住,您可能还希望通过
PARTITION BY your_grouping
来确保组中的第一行不会从另一个组中提取先前的值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.