Contents

Nth Higthest Salary

   Apr 16, 2023     1 min read

Nth Higthest Salary

문제

177-1.jpg
177-2.jpg

코드

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 함수 사용해서 풀기
Example
// 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

수행결과

177result.jpg