I need to fetch a number of rows between two column values, using a defined step value. For example, if the table looks like this:
Id Name
-----------------------
1 Maria Anders
2 Christina Berglund
3 Francisco Chang
4 Roland Mendel
5 Diego Roel
6 Eduardo Saavedra
7 Helen Bennett
8 Philip Cramer
and First = 3, Last = 7, Step = 2, query should return:
Id Name
-----------------------
3 Francisco Chang
5 Diego Roel
7 Helen Bennett
I was thinking of using a modulo to specify which columns should be returned, with something like:
SELECT *
FROM Table
WHERE (i-3) % 2 = 0
This approach will result in SQL Server iterating through the entire table and calculating the expression for each item. Since I expect to have relatively large step values, I would like to know if there is a strategy which would avoid this (possible using an index to “skip” items).
Is there a better (read: faster) way of doing this? (I am using MS SQL Server 2008 R2)
1 Answer