INSERT INTO #Employee(Name, Salary)VALUES('Ram',50000)
INSERT INTO #Employee(Name, Salary)VALUES('Shyam',40000)
INSERT INTO #Employee(Name, Salary)VALUES('Ghanshyam',40000)
INSERT INTO #Employee(Name, Salary)VALUES('Sita',30000)
INSERT INTO #Employee(Name, Salary)VALUES('Gita',20000)
INSERT INTO #Employee(Name, Salary)VALUES('Pranita',1000)
SELECT * FROM #Employee
--2nd highest
SELECT MAX(Salary) FROM #Employee WHERE Salary < (SELECT MAX(Salary) FROM #Employee)
--Change highlighted color number to get the N number of highest
SELECT TOP 1 *
FROM (
SELECT DISTINCT TOP 2 Salary
FROM #Employee
ORDER BY Salary DESC
) A
ORDER BY Salary ASC
--OR
SELECT DISTINCT Salary
FROM #Employee Emp1
WHERE 2 = (
SELECT COUNT(DISTINCT Emp2.Salary)
FROM #Employee Emp2
WHERE Emp2.Salary >= Emp1.Salary
)
--OFFSET
--N number
highest using CTE
--Change highlighted color number to get the N number of highest
;WITH RESULT
AS
(
SELECT Salary, DENSE_RANK() OVER(ORDER BY Salary DESC) AS 'DENSERANK'
FROM #Employee
)
;WITH RESULT
AS
(
SELECT Salary, DENSE_RANK() OVER(ORDER BY Salary DESC) AS 'DENSERANK'
FROM #Employee
)
SELECT TOP 1 * FROM RESULT WHERE DENSERANK = 2
--Change highlighted color number to get the N number of highest
SELECT DISTINCT Salary
FROM #Employee
ORDER BY Salary DESC
OFFSET 2-1 ROWS
SELECT DISTINCT Salary
FROM #Employee
ORDER BY Salary DESC
OFFSET 2-1 ROWS
FETCH NEXT 1 ROWS ONLY
No comments:
Post a Comment