How to Find Top N records using SQL

In this article we will see how to Find Top N records using SQL Server. Top –N queries that limit the result set to a specific number of rows. 

Top N Without Grouping

Top N Without Grouping – in this query its get the department wise employee list with grouping.

Select top 3 d.GroupName,e.JobTitle, p.Firstname,p.Lastname  from [Person].[Person] p inner join [HumanResources].[Employee] e 
on(p.BusinessEntityID = e.BusinessEntityID) inner join  [HumanResources].[EmployeeDepartmentHistory] h
on(e.BusinessEntityID=h.BusinessEntityID) inner join [HumanResources].[Department] d on(d.DepartmentID=h.DepartmentID)

Example-2

Top N With Grouping

Top N With Grouping – Its fetch the department wise employee list with grouping.

select  d.GroupName,e.JobTitle, p.Firstname,p.Lastname ,
ROW_NUMBER() over (partition by d.groupname order by d.groupname asc) as department_rank 
from [Person].[Person] p inner join [HumanResources].[Employee] e 
on(p.BusinessEntityID = e.BusinessEntityID) inner join  [HumanResources].[EmployeeDepartmentHistory] h
on(e.BusinessEntityID=h.BusinessEntityID) inner join [HumanResources].[Department] d on(d.DepartmentID=h.DepartmentID)

Leave a Reply

Your email address will not be published. Required fields are marked *