You could use ROW_NUMBER()
with a ORDER BY
clause in sub-query and use this column in replacement of TOP N
. This can be explained step-by-step.
See the below table which have two columns NAME
and DT_CREATED
.
If you need to take only the first two dates irrespective of NAME
, you could use the below query. The logic has been written inside query
-- The number of records can be specified in WHERE clause
SELECT RNO,NAME,DT_CREATED
FROM
(
-- Generates numbers in a column in sequence in the order of date
SELECT ROW_NUMBER() OVER (ORDER BY DT_CREATED) AS RNO,
NAME,DT_CREATED
FROM DEMOTOP
)TAB
WHERE RNO<3;
RESULT
In some situations, we need to select TOP N
results respective to each NAME
. In such case we can use PARTITION BY
with an ORDER BY
clause in sub-query. Refer the below query.
-- The number of records can be specified in WHERE clause
SELECT RNO,NAME,DT_CREATED
FROM
(
--Generates numbers in a column in sequence in the order of date for each NAME
SELECT ROW_NUMBER() OVER (PARTITION BY NAME ORDER BY DT_CREATED) AS RNO,
NAME,DT_CREATED
FROM DEMOTOP
)TAB
WHERE RNO<3;
RESULT