Skip to content
Advertisement

Select Top N rows plus another Select based on previous result

I am quite new to SQL.

I have a MS SQL DB where I would like to fetch the top 3 rows with datetime above a specific input PLUS get all the rows where the datetime value is equal to the last row of the previous fetch.

Here is my current request to fetch the 3 rows.

Here I would like to get in one request the last 4 rows.

Thanks for your help

Advertisement

Answer

One possibility, using ROW_NUMBER:

Matching records should be in the first 3 rows or should have timestamps equal to the timestamp in the third row. We can combine these conditions by restricting to timestamps equal or before the timestamp in the third row.

Or maybe use TOP 3 WITH TIES:

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement