๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

SQL

[SQL] Second Highest Salary(Leetcode - 176๋ฒˆ)

๋ฐ˜์‘ํ˜•

๐Ÿ”Š ๋ณธ ํฌ์ŠคํŒ…์—์„œ ์‚ฌ์šฉ๋˜๋Š” ํ…Œ์ด๋ธ”์˜ ์ž๋ฃŒ์™€ ์ถœ์ฒ˜๋Š” Leetcode์ž„์„ ๋ฐํž™๋‹ˆ๋‹ค. ๋” ๋‹ค์–‘ํ•œ SQL ๋ฌธ์ œ๋ฅผ ํ’€์–ด๋ณด์‹œ๋ ค๋ฉด Leetcode ์‚ฌ์ดํŠธ๋ฅผ ๋ฐฉ๋ฌธํ•ด ๋ณด์„ธ์š”!

 

Leetcode ์‚ฌ์ดํŠธ

 

์ด๋ฒˆ ํฌ์ŠคํŒ…์€ Leetcode 176๋ฒˆ ๋ฌธ์ œ์ธ 'Second Highest Salary' ๋ฌธ์ œ๋ฅผ ํ’€์–ด๋ณด๋ ค ํ•œ๋‹ค. ๋ฌธ์ œ์˜ ๋‚œ์ด๋„๋Š” ๋น„๊ต์  ์–ด๋ ต์ง€ ์•Š์ง€๋งŒ ์ด ๋ฌธ์ œ๋ฅผ ํฌ์ŠคํŒ…์— ๊ฒŒ์‹œํ•˜๋Š” ์ด์œ ๋Š” LIMIT ๊ณผ OFFSET ๋ฌธ๋ฒ•์„ ์‚ฌ์šฉ ์‹œ ์ฃผ์˜ํ•ด์•ผ ํ•  ์ ์„ ์†Œ๊ฐœํ•˜๊ธฐ ์œ„ํ•จ์ด๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

1. ์„œ๋ธŒ์ฟผ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•ด์„œ ํ’€๊ธฐ!

์šฐ์„  ๋ฌธ์ œ์—์„œ ์š”๊ตฌํ•˜๋Š” ๊ฒƒ์€ ๋ฌธ์ œ ์ด๋ฆ„์—๋„ ๋‚˜์™€ ์žˆ๋“ฏ์ด 2๋ฒˆ์งธ๋กœ ๊ฐ€์žฅ ๋†’์€ Salary๋ฅผ ์ถœ๋ ฅํ•˜๊ธฐ๋งŒ ํ•˜๋ฉด ๋œ๋‹ค. ๋ฌธ์ œ์—์„œ ์ฃผ์–ด์ง„ ํ…Œ์ด๋ธ” ํ˜•ํƒœ๋ฅผ ์ž์„ธํžˆ ๋“ค์—ฌ๋‹ค๋ณด์ž.

 

Leetcode - 176๋ฒˆ ๋ฌธ์ œ

 

2๋ฒˆ์งธ๋กœ ๊ฐ€์žฅ ๋†’์€ Salary๋ฅผ ์ถœ๋ ฅํ•˜๊ธฐ ์œ„ํ•œ ์ •์„์˜ ๋ฐฉ๋ฒ•์€ "1๋ฒˆ์งธ๋กœ ๊ฐ€์žฅ ๋†’์€ Salary๋ฅผ ์ œ์™ธํ–ˆ์„ ๋•Œ์˜ ๊ฐ€์žฅ ๋†’์€ Salary๊ฐ’์ด 2๋ฒˆ์งธ๋กœ ๊ฐ€์žฅ ๋†’์€ ๊ฐ’์ผ ๊ฑฐ์ž–์•„!" ๋ผ๋Š” ์•„์ด๋””์–ด์—์„œ ์ถœ๋ฐœํ•  ์ˆ˜ ์žˆ๋‹ค. ๋”ฐ๋ผ์„œ ์„œ๋ธŒ์ฟผ๋ฆฌ๋ฅผ ํ™œ์šฉํ•˜๊ฒŒ ๋˜๋ฉด ํ’€์ด๊ฐ€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

 

SELECT MAX(Salary) AS SecondHighestSalary
FROM Employee
WHERE Salary < (SELECT MAX(Salary)
                FROM Employee)

2. LIMIT ๊ณผ OFFSET ํ™œ์šฉํ•˜๊ธฐ

ํ•„์ž๋Š” ์„œ๋ธŒ์ฟผ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•ด์„œ ํ’€์–ด๋ณธ ํ›„ ์–ผ๋งˆ์ „์— ๋ฐฐ์šด LIMIT๊ณผ OFFSET์„ ํ™œ์šฉํ•ด์„œ ํ’€ ์ˆ˜ ์žˆ์ง€ ์•Š์„๊นŒ ์ƒ๊ฐํ–ˆ๊ณ  ์‹ค์ฒœํ•ด๋ณด์•˜๋‹ค. ํ•˜์ง€๋งŒ ํ•ด๋‹น ๋ฌธ์ œ์˜ ๋ฐ˜๋ก€์— ๋œ์ปฅ ๋ง‰ํ˜€๋ฒ„๋ ธ๋‹ค. ์šฐ์„  LIMIT๊ณผ OFFSET์„ ํ™œ์šฉํ•œ ํ’€์ด๋ฅผ ์‚ดํŽด๋ณด์ž.

 

-- LIMIT๋งŒ ์‚ฌ์šฉํ•œ SQL ๊ตฌ๋ฌธ
SELECT Salary AS SecondHighestSalary
FROM Employee
ORDER BY Salary DESC
LIMIT 1, 1

 

-- LIMIT & OFFSET ๋ชจ๋‘ ํ™œ์šฉํ•œ SQL ๊ตฌ๋ฌธ
SELECT Salary AS SecondHighestSalary
FROM Employee
ORDER BY Salary DESC
LIMIT 1 OFFSET 1

 

์œ„ 2๊ฐœ์˜ ํ’€์ด๋Š” ํ•ด๋‹น ๋ฌธ์ œ์˜ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค์—๋Š” ์„ฑ๊ณตํ•˜์ง€๋งŒ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๋‹ค๋ฅธ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค์—๋Š” Null์„ ๋ฐ˜ํ™˜ํ•˜์ง€ ๋ชปํ•œ๋‹ค. 

 

Id Salary
1 100

์ฆ‰, ์œ„ ํ…Œ์ด๋ธ” ์ฒ˜๋Ÿผ ์ƒ์œ„ 2๋ฒˆ์งธ๋กœ ๋†’์€ Salary ๊ฐ’์ด ์กด์žฌํ•˜์ง€ ์•Š์„ ๋•Œ(Null ์ผ๋•Œ) LIMIT๊ณผ OFFSET์„ ์‚ฌ์šฉํ•œ ํ’€์ด๋“ค์€ Null์„ ๋ฐ˜ํ™˜ํ•˜์ง€ ๋ชปํ•œ๋‹ค.

 

๋ฐ˜์‘ํ˜•