코딩 연습/SQL
사용자 정의 함수
썬2
2022. 8. 14. 12:27
사용자 정의 함수: https://www.mysqltutorial.org/mysql-stored-function/
if statement: https://www.mysqltutorial.org/mysql-if-statement/
case vs if statement vs if function 차이
참고: https://stackoverflow.com/questions/30047983/mysql-case-vs-if-statement-vs-if-function
조건이 여러개이고 순차적이라면 case 쓰기!
(if function은 standard sql이 아니라서 postgresql에는 적용 안된다.)
177. Nth Highest Salary
https://leetcode.com/problems/nth-highest-salary/
사용자 정의 함수를 이용해서 코드 짜보기.
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 함수를 이용해서 코드 짜보기.
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
DECLARE A INT;
SET A = N - 1;
RETURN (
select distinct salary
from employee
order by salary desc
limit A, 1
);
END
limit N, 1 -> N+1의 값을 가져오기 == limit 1 offset N -> N개는 없애고(offset) 1개를 가져와라.
가져온 변수를 바로 쓸 수 없어서 declare와 set을 해주기.