Open hdonghun opened 2 years ago
MySQL 답안(CASE로 풀기) :
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
기본 예시 MySQL FUNCTION
CREATE FUNCTION CustomerLevle(credit DECIMAL(10,2)) RETURNS VARCHAR(20) DETERMINISTIC BEGIN DECLATRE Level VARCHAR(20); #변수선언
IF credit > 50000 THEN
SET Level = 'PLATINUM';
ELSEIF(credit <= 50000 AND credit >= 10000) THEN
SET Level = 'GOLD';
ELSELF(credit < 10000 THEN
SET Level = 'SILVER'; THEN
END IF;
--return the customer level
RETURN(Level);
END
MySQL 답안(IF로 풀기) : 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
MySQL 답안(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
(새로운 변수를 만들어줘서 하는법 : DECLARE A INT; SET A = N-1; or SET으로 N의 값만 변경해줘서 하는 법 : SET N = N-1; )
LeetCode - 177. Nth Highest Salary 출처 : https://leetcode.com/problems/nth-highest-salary/
Input: Employee table: +----+--------+ | id | salary | +----+--------+ | 1 | 100 | | 2 | 200 | | 3 | 300 | +----+--------+
n = 2 Output: +------------------------+ | getNthHighestSalary(2) | +------------------------+ | 200 | +------------------------+
Example 2:
Input: Employee table: +----+--------+ | id | salary | +----+--------+ | 1 | 100 | +----+--------+
n = 2 Output: +------------------------+ | getNthHighestSalary(2) | +------------------------+ | null | +------------------------+