기본구조
CREATE FUNCTION 'function name' ('parameter name', 'datatype')
RETURNS 'datatype' (DETERMINSTIC)
BEGIN
DECLARE 'varialbe name' 'datatype';
SET ;
RETURN (Query) / 'variable name';
END
사용방법
- SELECT 'function name' (parameter)
예제 문제
Table: Employee
+-------------+------+
| Column Name | Type |
+-------------+------+
| id | int |
| salary | int |
+-------------+------+
id is the primary key column for this table.
Each row of this table contains information about the salary of an employee.
Write an SQL query to report the nth highest salary from the Employee table. If there is no nth highest salary, the query should report null.
The query result format is in the following example.
Example 1:
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 |
+------------------------+
코드
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
RETURN (
# Write your MySQL query statement below.
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
'SQL > MySQL' 카테고리의 다른 글
MySQL 코테준비 - 자동차 대여 기록에서 장기/단기 대여 구분하기 (2) | 2024.01.11 |
---|---|
MySQL 코테준비 - 조건에 부합하는 중고거래 상태 조회하기 (0) | 2024.01.11 |
[MySQL] 윈도우함수로 예제 문제 풀어보기 (LeetCode - department-highest-salary) (0) | 2022.02.25 |
[MySQL] 윈도우함수로 예제 문제 풀어보기 (LeetCode - consecutive-numbers) (0) | 2022.02.25 |
[MySQL] 윈도우함수(Window Functions) (0) | 2022.02.25 |