SQL server find nth Greatest row

1
22

Image

 

Imaging there is a table named customers and we need to fethch the n th highest row.

Customers have a column cust_id (identity column) which may not be uniform

Query

select t.* from (select *, row_number() over ( order by cust_id desc ) as rn from customers ) as t where t.rn=5

Here inner query will act as a virtual table and row_number() will return number of row when sorted in descending order WRT cust_id and finally where clause filter row which came in 5th position

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here