Showing posts with label n-th. Show all posts
Showing posts with label n-th. Show all posts

Tuesday, March 27, 2012

Filter

I need a query that returns every n record from the database and the last record.

For every n-th is easy, but I need a

WHERE Index % n = 0

but I need a last one too.

Any Help.

How about a UNION statement? The new code you want is in green.

SELECT Col1, idx

FROM MyTable

WHERE idx % 12 = 0

UNION

SELECT Col1, idx

FROM MyTable

WHERE idx = (SELECT MAX(idx) FROM MyTable)

|||

In 2005, you can do something like:

select *
from (

select row_number() over (order by object_id) as rowNum,
object_id
from sys.objects

) as objects
where rowNum % 5 = 0
or rowNum = (select count(*) from sys.objects)

There is a (more messy) way to do it in 2000 also. The key is that tables don't have order, so you will need to define an order in order to calculate N.