I have a logging table used for device “heartbeats”. I have these network devices that check-in/heartbeat with the server every 10 minutes. We are wanting statistics on when they miss their scheduled check-in time. I have a query that can do this on a per-device basis, but I need it to be modified to handle across all devices.
The heartbeat table looks like this:
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]
Device checks into the server, the server adds a row to this table with its Id, the CheckinTime and the device’s runtime (a hardware value sent by the device). The query I have currently looks like this:
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;
This query is limited to a single specified device. Example results look like this:
stats
----------------- ----
< 10 minutes: 1536
10 - 11 minutes: 425
11 - 12 minutes: 952
+12 minutes: 160
Ideally, I’m only concerned with check-ins greater than 12 minutes. So, what I was wanting was a list of devices who have check-ins greater than 12 minutes, ordered by their counts. This will allow me to see the top 10 or 20 devices that have greater than 12 minute check-in times, alerting me to problem devices. Something like:
DeviceId CheckinsOver12Mins
---------- -------------------
1112 160
1108 152
15 114
106 86
Suggestions?