views:

241

answers:

1

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?

+1  A: 

Try this:

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

Note: Don't have test data -- did not test, might have typos.

It should be the y CTE could be removed and changed to making it a smaller query:

select deviceID, count(deviceID) as [Checkins over 12 mins] 
FROM x 
GROUP BY deviceID
HAVING d > 12
Hogan
That works! Thank you VERY much.
Todd Brooks
YW, My pleasure.
Hogan