MSSQL - Limit Query to last 5 records of group by I have a data table that is expected to grow at about 20,000 records a day

I'm wanting to sum the last five 'detector_record_status' for each 'installation_id''s 'detector_id'.

If the sum of the last 5 (detector_record_status) is >=3 then its deemed Active.

eg
installation_id
detector_id
Active = sum(detector_record_status) =&gt; 3

installation_id|  detector_id  |  Status
            1  |            8  |  Active


I do how to limit to 5 records for each 'detector_id' of the 'installation_id'
And to show 'Active' rather than the sum(detector_record_status)

I've created a sqlfiddle 
http://sqlfiddle.com/#!18/3f65f/3/0
You can accomplish this using a Common Table Expression (CTE) that assigns a row number to each detector_record_id partitioned on each installation_id and detector_id.

Order it descending and return the top 5 in your outer query. This grabs the most recent 5 records (based on detector_record_id) per installation_id and detector_id. The outer query then sums the detector_record_status and a simple HAVING clause eliminates those that don't meet the "Active" threshold.

As your table grows, it will become important to monitor the inner SELECT performance as it will be returning all rows from detector_record and this could become slow to execute.

Example

;WITH dRecords AS (
  SELECT installation_id,
    detector_id,
    detector_record_status,
    ROW_NUMBER() OVER (PARTITION BY installation_id, detector_id ORDER BY detector_record_id DESC) AS [Rn]
  FROM detector_record
)
SELECT
  installation_id,
  detector_id,
  SUM(detector_record_status) as Activity
FROM dRecords
WHERE [Rn] &lt;= 5
GROUP BY   installation_id, detector_id
HAVING SUM(detector_record_status) &gt;= 3
ORDER BY   installation_id