Saturday, January 20, 2018

How to retrieve the Minimum and Maximum Salary drawing Employee Details by Department in SQL Server

T-SQL to Query to retrieve the Minimum and Maximum Salary drawing Employee Details by Department 
Scenario :
Suppose we have the Employee Table and a Department Table as follows, from which we want Query the following details.
1) The details of the Employees who are drawing Highest/Maximum and Lowest/Minimum Salary.
2) The details of the Employees who are drawing Highest/Maximum and Lowest/Minimum Salary by Department.

Select * From Tbl_Emp


Select * From Tbl_Dept

1) Query to retrieve the details of the Employees who are drawing Highest/Maximum and Lowest/Minimum Salary.

With MyCTE AS
(
Select  S1.RowNum, S1.Emp_Id,S1.EmpName, D.DeptName,S1.NetSal 
        From  
               Select ROW_NUMBER() OVER ( Order By NetSal ) as RowNum, 
                   * From Tbl_Emp
 ) 
          S1 Inner Join Tbl_Dept D
On S1.Dept_Id=D.DeptId
)
Select Emp_Id,EmpName,DeptName,NetSal  From MyCTE 
Where RowNum = (Select Min(RowNum) from MyCTE) 
OR RowNum = (Select Max(RowNum) from MyCTE) 
;

Result:
Please note that this result shows the Employees who are drawing Maximum and Minimum Salary out of all Employees of all Departments.


2) Query to retrieve the details of the Employees who are drawing Highest/Maximum and Lowest/Minimum Salary by Department.
With MyCTE AS
(
Select  S1.RowNum, S1.Emp_Id,S1.EmpName, D.DeptName,S1.NetSal 
        From  
Select ROW_NUMBER() OVER ( PARTITION BY Dept_Id Order By NetSal ) as RowNum, * From Tbl_Emp
   ) 
          S1 Inner Join Tbl_Dept D
 On S1.Dept_Id=D.DeptId
)
Select Emp_Id,EmpName,DeptName,NetSal  From MyCTE 
Where RowNum IN (Select Min(RowNum) from MyCTE Group By DeptName
OR RowNum IN (Select Max(RowNum) from MyCTE Group By DeptName
;

Result:

Note:
Here I used the Common Table Expressions(CTEs) method to handle the Scenario. You achieve the same using different Methods as well.

--------------------------------------------------------------------------------------------------------
Thanks, TAMATAM ; Business Intelligence & Analytics Professional
-------------------------------------------------------------------------------------------------------
-

No comments:

Post a Comment

Hi User, Thank You for visiting My Blog. Please post your genuine Feedback or comments only related to this Blog Posts. Please do not post any Spam comments or Advertising kind of comments which will be Ignored.

Featured Post from this Blog

How to compare Current Snapshot Data with Previous Snapshot in Power BI

How to Dynamically compare two Snapshots Data in Power BI Scenario: Suppose, we have a sample Sales data, which is stored with Monthly Snaps...

Popular Posts from this Blog