[LeetCode] 176. Second Highest Salary
๐ข ๋ณธ ํฌ์คํ ์ ํ์ฉ๋๋ ๊ธฐ๋ณธ ๋ฌธ์ ๋ฐ ์๋ฃ ์ถ์ฒ๋
๋ฆฌํธ์ฝ๋ Problems, https://leetcode.com/problemset/all/์์ ๋ฐํ๋๋ค.
โ ๋ฌธ์
https://leetcode.com/problems/second-highest-salary/
Second Highest Salary - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
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 second highest salary from the Employee table.
If there is no second highest salary, the query should report null.
The query result format is in the following example.
โ ํ์ด
Employee ํ ์ด๋ธ์์ ๋๋ฒ์จฐ๋ก ๋์ ์๊ธ์ ์ถ๋ ฅํ๋๋ฐ ๋๋ฒ์จฐ๋ก ๋์ ๊ฐ์ด ์๋ค๋ฉด Null์ ๋ฐํํด๋ผ
(ํ์ด1)
LIMIT๊ณผ OFFSET ์ฌ์ฉ
LIMIT x, y
> ( x + 1 ) ๋ฒ์งธ ํ๋ถํฐ y ๊ฐ ๊ฐ์ ธ์จ๋ค.
SELECT salary
FROM Employee
ORDER BY salary DESC
LIMIT 1, 1;
> ๋๋ฒ์งธ ํ๋ถํฐ 1๊ฐ๋ฅผ ๊ฐ์ ธ์ค๋๋ฐ ๋๋ฒ์งธ ํ์ด ์์ผ๋ฉด ๊ฐ์ ธ์ฌ ์ ์๋ค.
LIMIT x OFFSET y
> ( x + 1 ) ๋ฒ์งธ ํ๋ถํฐ y ๋ฒ์งธ ํ์ ๊ฐ์ ธ์จ๋ค.
SELECT salary
FROM EMPLOYEE
ORDER BY salary DESC
LIMIT 1 OFFSET 1;
(ํ์ด2)
์๋ธ์ฟผ๋ฆฌ ์ฌ์ฉํ๊ธฐ
SELECT MAX(salary) SecondHighestSalary
FROM employee
WHERE salary < (SELECT MAX(salary)
FROM employee);
> employee ์ ์ฒด์์ ์ต๋ salary๋ฅผ ์ฐพ์์, ๋๋ฒ์งธ๋ก ๋์ Salary๋ฅผ ์ฐพ์ ๋ where์ ์ ์กฐ๊ฑด์ผ๋ก ์ค๋ค.