How can I return every nth record from a sub query based on a numerical parameter that I supply?
For example, I may have the following query:
Select B.name
from (Select row_number() over (order by ordering) as row_num,
A.name
from (Select name,'P1' as ordering
from [dbo].[every_2nd_record]
) A
) B
where B.row_num%2=0
This is where ROW_NUMBER can help. It requires an order-by clause but this is okay because an order-by is present (and required to guarantee a particular order).
SELECT t.id, t.key
FROM
(
SELECT id, key, ROW_NUMBER() OVER (ORDER BY key) AS rownum
FROM datatable
) AS t
WHERE t.rownum % 30 = 0 -- or % 40 etc
ORDER BY t.key
You don't have to use row number, any integer field will do. On most tables we have an autonumber field. For simplicity, I will call it ID. To display every 13th record:
Select ID, LastName, FirstName FROM Users WHERE ID%13 = 0 ORDER BY ID