Saturday, 21 January 2023

SQL Server Query related questions

1:- Finding nth highest salary in SQL?

Below is the Table structure:

Create table Employees
(
     ID int primary key identity,
     FirstName nvarchar(50),
     LastName nvarchar(50),
     Gender nvarchar(50),
     Salary int
)
GO

Insert into Employees values ('Suraj', 'Kumar', 'Male', 70000)
Insert into Employees values ('Rahul', 'Mad', 'Male', 60000)
Insert into Employees values ('Steve', 'jobs', 'Male', 46000)
Insert into Employees values ('Mahesh', 'kumar', 'Male', 70000)
Insert into Employees values ('Suresh', 'sinha', 'Male', 45000)
Insert into Employees values ('Ravi', 'kukreja', 'Female', 30000)
Insert into Employees values ('Priyanka', 'singh', 'Female', 36000)
Insert into Employees values ('Riya', 'Mishra', 'Male', 90000)
GO

Here we are finding 2nd highest Salary from Employee Table.

Using  Sub-Query with Max function

  Select Max(Salary) from Employee where Salary < (Select Max(Salary) from Employee)

Using  Sub-Query 

  SELECT TOP 1 SALARY
  FROM (
        SELECT DISTINCT TOP 2 SALARY
        FROM EMPLOYEE
        ORDER BY SALARY DESC
        ) RESULT
  ORDER BY SALARY ASC;

Using CTE

  WITH RESULT AS
  (
      SELECT DENSE_RANK() OVER (ORDER BY SALARY DESC) AS DENSERANK, SALARY
      FROM EMPLOYEES
  )
  SELECT TOP 1 SALARY
  FROM RESULT
  WHERE DENSERANK = 2

2:- Delete duplicate rows from table

WITH tblTemp as
(
   SELECT ROW_NUMBER() Over(PARTITION BY NameDepartment ORDER BY Name)
   AS RowNumber, * FROM emp
)
DELETE FROM tblTemp where RowNumber >1



0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (49) CD (1) CI (2) CloudComputing (2) Coding (8) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (19) Entity Framework (4) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives