Nth Higthest Salary
문제
코드
MySQL
CASE WHEN 사용해서 풀기
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
RETURN (
SELECT CASE WHEN COUNT(SUB.SALARY) < N THEN NULL
ELSE MIN(SUB.SALARY)
END
FROM (
SELECT DISTINCT SALARY
FROM EMPLOYEE
ORDER BY SALARY DESC
LIMIT N
) SUB
);
END
IF 함수 사용해서 풀기
// IF (condition, value_if_true, value_if_false)
SELECT IF(500<1000, "YES", "NO")
SELECT IF(500<1000, "YES", NULL)
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
RETURN (
SELECT IF(COUNT(SUB.SALARY) < N, NULL, MIN(SUB.SALARY))
FROM (
SELECT DISTINCT SALARY
FROM EMPLOYEE
ORDER BY SALARY DESC
LIMIT N
) SUB
);
END
LIMIT OFFSET 사용해서 풀기
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
SET N = N-1;
RETURN (
SELECT DISTINCT SALARY
FROM EMPLOYEE
ORDER BY SALARY DESC
LIMIT 1 OFFSET N
);
END