hdonghun / SQL

1 stars 0 forks source link

인프런 - SQL 고급 강의 듣고 공부 07 _ 사용자 정의 함수로 풀기 #31

Open hdonghun opened 2 years ago

hdonghun commented 2 years ago

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 | +------------------------+

hdonghun commented 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

hdonghun commented 2 years ago

기본 예시 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

hdonghun commented 2 years ago

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

hdonghun commented 2 years ago

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

parameter이 N이라고 선언하였고, 밑에 코드를 작성중 N을 직접적으로 N-1이라고 바꿔줄수는 없고, DECALRE와 SET을 통해서 변경해줄수있다.

(새로운 변수를 만들어줘서 하는법 : DECLARE A INT; SET A = N-1; or SET으로 N의 값만 변경해줘서 하는 법 : SET N = N-1; )