Thursday, March 16, 2017

Get Nth Row From SQL, Database

To Get the nth row from your table to the following steps
  • Find all the distinct values count
  • Write a self query that test the grater then condition
  • Now you will get the same row that you requested
For Ex:

Create table Employee(Id int identity(1,1),Name varchar(10),Salary int);

Insert into Employee values ('A',10000)
Insert into Employee values ('B',10001)
Insert into Employee values ('C',10002)
Insert into Employee values ('D',10003)
Insert into Employee values ('E',10004)
Insert into Employee values ('F',10005)
Insert into Employee values ('G',10006)
Insert into Employee values ('H',10007)
Insert into Employee values ('I',10008)
Insert into Employee values ('J',10009)


Declare @N int = 9
SELECT * FROM Employee E1
WHERE (@N-1) =
(SELECT COUNT(DISTINCT(E2.Salary)) FROM Employee E2 WHERE E2.Salary < E1.Salary)

No comments:

Post a Comment