Note that there are some explanatory texts on larger screens.

plurals
  1. POSQL Query to aggregate DateDiff greater than given value
    primarykey
    data
    text
    <p>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.</p> <p>The heartbeat table looks like this:</p> <pre><code>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] </code></pre> <p>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:</p> <pre><code>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 &lt; 10 THEN ' &lt; 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; </code></pre> <p>This query is limited to a single specified device. Example results look like this:</p> <pre><code>stats ----------------- ---- &lt; 10 minutes: 1536 10 - 11 minutes: 425 11 - 12 minutes: 952 +12 minutes: 160 </code></pre> <p>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:</p> <pre><code>DeviceId CheckinsOver12Mins ---------- ------------------- 1112 160 1108 152 15 114 106 86 </code></pre> <p>Suggestions?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload