Sql-server – Select fixed number of records/rows from growing table from SQL Server

querysql server

Background: A SQL-Server database table is used to store weekly reports of some system memory usage, meaning that each week a new table row/record/line is inserted.

The question is how a fixed number (e.g. 5 records) of records can be queried, with the side-condition that those records are equally spaced within the time-range.

if this was the table

id | memory
----------- 
01  1231
02  1241
03  1260
04  1300
[.... other 92 rows ...]
97  2001
98  2002
99  2020

and with said 5 records I would like have a table as such

id | memory
----------- 
01  1231
25  1600
50  1800
75  1900
99  2020

since it would most represent the overall picture of the data.

Best Answer

There's probably a more elegant way to achieve this but it can be done by using the NTILE function inside a CTE.

WITH cte AS (

  SELECT NTILE(5) OVER (ORDER BY id asc) AS dist,
  memory
  FROM TABLE)

  SELECT TOP 1 id, memory FROM cte WHERE dist = 1

  UNION

   SELECT TOP 1 id, memory FROM cte WHERE dist = 2

  UNION

   SELECT TOP 1 id, memory FROM cte WHERE dist = 3

  UNION

   SELECT TOP 1 id, memory FROM cte WHERE dist = 4

  UNION

   SELECT TOP 1 id, memory FROM cte WHERE dist = 5;