Growth ๐ŸŒณ/Practice ๐Ÿ’ป

[LeetCode] 176. Second Highest Salary

์ธ” 2022. 8. 26. 18:26

๐Ÿ“ข ๋ณธ ํฌ์ŠคํŒ…์— ํ™œ์šฉ๋˜๋Š” ๊ธฐ๋ณธ ๋ฌธ์ œ ๋ฐ ์ž๋ฃŒ ์ถœ์ฒ˜๋Š”

       ๋ฆฌํŠธ์ฝ”๋“œ 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์ ˆ์— ์กฐ๊ฑด์œผ๋กœ ์ค€๋‹ค.