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.

| rowId | Timestamp                | data |
|-------|--------------------------|------|
| rsg   | 2019-01-01T00:00:00.000Z | 120  |
| zqd   | 2020-01-01T00:00:00.000Z | 36   |
| ylp   | 2020-01-01T00:00:00.000Z | 48   |
| abt   | 2022-01-01T00:00:00.000Z | 53   |
| zio   | 2022-01-01T00:00:00.000Z | 12   |

Here is my current request to fetch the 3 rows.

    SELECT
      TOP 3 *
    FROM
      Table
    WHERE
      Timestamp >= '2020-01-01T00:00:00.000Z'
    ORDER BY
      Timestamp ASC

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

Thanks for your help

Advertisement

Answer

One possibility, using ROW_NUMBER:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (ORDER BY Timestamp) rn
    FROM yourTable
)

SELECT *
FROM cte
WHERE
    Timestamp <= (SELECT Timestamp FROM cte WHERE rn = 3);

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:

SELECT TOP 3 WITH TIES *
FROM yourTable
ORDER BY Timestamp;
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement