我有一个用于设备“heartbeats”的日志记录表。我有这些网络设备每10分钟与服务器签入/心跳。我们想要了解他们何时错过预定登记入住时间的统计数据。我有一个查询,可以在每个设备的基础上执行此操作,但我需要对其进行修改以处理所有设备。
心跳表如下所示:
CREATE TABLE [dbo].[DeviceHeartbeat](
[Id] [int] IDENTITY(1,1) NOT NULL,
[DeviceId] [int] NULL,
[CheckinTime] [datetime] NULL,
[Runtime] [int] NULL,
PRIMARY KEY CLUSTERED
([Id] ASC)) ON [PRIMARY]
设备检查服务器,服务器向该表添加一行,包括其Id,CheckinTime和设备的运行时(设备发送的硬件值)。 我目前的查询看起来像这样:
WITH t AS
(
SELECT Checkintime, rn = ROW_NUMBER() OVER (ORDER BY Checkintime)
FROM DeviceHeartbeat
WHERE DeviceId = 1112
),
x AS
(
SELECT d = DATEDIFF(MINUTE, t1.Checkintime, t2.Checkintime)
FROM t AS t1
INNER JOIN t AS t2
ON t1.rn = t2.rn - 1
),
y AS
(
SELECT stats = CASE WHEN d < 10 THEN ' < 10 '
WHEN d BETWEEN 10 AND 11 THEN '10 - 11 '
WHEN d BETWEEN 11 AND 12 THEN '11 - 12 '
ELSE '+12 ' END + ' minutes:'
FROM x
)
SELECT stats, COUNT(*) FROM y GROUP BY stats;
此查询仅限于单个指定的设备。示例结果如下所示:
stats
----------------- ----
< 10 minutes: 1536
10 - 11 minutes: 425
11 - 12 minutes: 952
+12 minutes: 160
理想情况下,我只关心超过12分钟的签到。所以,我想要的是一个设备列表,这些设备的签到时间超过12分钟,按其计数排序。这将允许我查看超过12分钟登记时间的前10或20个设备,提醒我有问题的设备。 类似的东西:
DeviceId CheckinsOver12Mins
---------- -------------------
1112 160
1108 152
15 114
106 86
建议?
答案 0 :(得分:2)
试试这个:
WITH t AS
(
SELECT Checkintime, DeviceID, rn = ROW_NUMBER() OVER (ORDER BY DeviceID, Checkintime)
FROM DeviceHeartbeat
),
x AS
(
SELECT t1.deviceID, d = DATEDIFF(MINUTE, t1.Checkintime, t2.Checkintime)
FROM t AS t1
INNER JOIN t AS t2
ON t1.rn = t2.rn - 1 and t1.DeviceID = t2.DeviceID
),
y AS
(
SELECT deviceID
FROM x
WHERE d > 12
)
select deviceID, count(deviceID) as [Checkins over 12 mins] FROM y GROUP BY deviceID
注意:没有测试数据 - 没有测试,可能有拼写错误。
应该删除y CTE并将其更改为使其成为较小的查询:
select deviceID, count(deviceID) as [Checkins over 12 mins]
FROM x
GROUP BY deviceID
HAVING d > 12