Monday, January 25, 2010

Second highest Salary


DECLARE @Employees TABLE(
EmployeeID INT IDENTITY,
EmployeeName VARCHAR(15),
Department VARCHAR(15),
Salary NUMERIC(16,2)
)

INSERT INTO @Employees VALUES('T Cook','Finance', 40000)
INSERT INTO @Employees VALUES('D Michael','Finance', 25000)
INSERT INTO @Employees VALUES('A Smith','Finance', 25000)
INSERT INTO @Employees VALUES('jj','Finance', 25000)
INSERT INTO @Employees VALUES('D Adams','Finance', 15000)

INSERT INTO @Employees VALUES('M Williams','IT', 80000)
INSERT INTO @Employees VALUES('D Jones','IT', 40000)
INSERT INTO @Employees VALUES('J Miller','IT', 50000)
INSERT INTO @Employees VALUES('L Lewis','IT', 50000)

INSERT INTO @Employees VALUES('A Anderson','Back-Office', 25000)
INSERT INTO @Employees VALUES('S Martin','Back-Office', 15000)
INSERT INTO @Employees VALUES('J Garcia','Back-Office', 15000)
INSERT INTO @Employees VALUES('T Clerk','Back-Office', 10000)

SELECT *
FROM
(
SELECT *, DENSE_RANK() OVER (PARTITION BY Department ORDER BY Salary DESC) AS EmpRank
FROM @Employees
) AS Employees
WHERE EmpRank = 2

No comments: