Growth ๐ŸŒณ/Practice ๐Ÿ’ป

1907. Count Salary Categories

์ธ” 2023. 9. 24. 21:43

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

       ๋ฆฌํŠธ์ฝ”๋“œ Problems, https://leetcode.com/problemset/all/์ž„์„ ๋ฐํž™๋‹ˆ๋‹ค.


โœ”๋ฌธ์ œ

https://leetcode.com/problems/count-salary-categories/description/

 

LeetCode - The World's Leading Online Programming Learning Platform

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: Accounts

Write a solution to calculate the number of bank accounts for each salary category. The salary categories are:

  • "Low Salary": All the salaries strictly less than $20000.
  • "Average Salary": All the salaries in the inclusive range [$20000, $50000].
  • "High Salary": All the salaries strictly greater than $50000.

The result table must contain all three categories. If there are no accounts in a category, return 0.

Return the result table in any order.


โœ” ํ’€์ด

  ๋ฌธ์ œ ์š”๊ตฌ์‚ฌํ•ญ  

Accounts ํ…Œ์ด๋ธ”์—์„œ ๋ฌธ์ œ์— ์ œ์‹œํ•˜๋Š” ์นดํ…Œ๊ณ ๋ฆฌ ๋ฒ”์ฃผ์— ๋”ฐ๋ฅธ ๊ณ„์ขŒ์ˆ˜๋ฅผ ๋ณด์—ฌ์ฃผ๋Š” ํ…Œ์ด๋ธ”์„ ์ถœ๋ ฅํ•˜๋˜, ๋ฒ”์ฃผ์— ํ•ด๋‹นํ•˜๋Š” ๊ณ„์ขŒ๊ฐ€ ์—†๋‹ค๋ฉด 0 ์œผ๋กœ ํ‘œ๊ธฐํ•ด์•ผ ํ•œ๋‹ค.

 

โ‘  ๊ฐ ์ˆ˜์ž…์ด ํ•ด๋‹นํ•˜๋Š” ๊ธ‰์—ฌ ์นดํ…Œ๊ณ ๋ฆฌ ๋ฒ”์ฃผ๋ฅผ ์ƒ์„ฑํ•˜๊ณ  ๋ฒ”์ฃผ๋ณ„ ๊ณ„์ขŒ ์ˆ˜๋ฅผ group by ๋กœ ๊ตฌํ•ด์ค€๋‹ค.

 โ˜… ์ตœ์ข… ์ถœ๋ ฅ์—์„œ๋Š” <โ‘ > ์ง‘๊ณ„๊ฐ’์—์„œ ํŠน์ • ๋ฒ”์ฃผ ์นดํ…Œ๊ณ ๋ฆฌ์— ํ•ด๋‹นํ•˜๋Š” ๊ณ„์ขŒ์ˆ˜๊ฐ€ ์—†๋‹ค๋ฉด ํ•ด๋‹น ์นดํ…Œ๊ณ ๋ฆฌ ๋ฒ”์ฃผ๋Š” ์ถœ๋ ฅ๋˜์ง€ ์•Š๋Š” ๊ฒƒ์„ ๊ณ ๋ คํ•ด์•ผ ํ•œ๋‹ค.

โ‘ก ๋ชจ๋“  ์นดํ…Œ๊ณ ๋ฆฌ(salary) ๋ฒ”์ฃผ๋ฅผ ์ถœ๋ ฅํ•˜๊ธฐ ์œ„ํ•ด ์นดํ…Œ๊ณ ๋ฆฌ ๋ฒ”์ฃผ ์ „์ฒด๋ฅผ ๊ฐ’์œผ๋กœ ๊ฐ–๋Š” category ์ปฌ๋Ÿผ์„ ์ถœ๋ ฅํ•˜๋Š” ํ…Œ์ด๋ธ”์„ ๋งŒ๋“ค์–ด์ค€๋‹ค.

โ‘ข <โ‘ก> ํ…Œ์ด๋ธ”์„ ๊ธฐ์ค€์œผ๋กœ left join ํ•ด์„œ ๊ธ‰์—ฌ ์นดํ…Œ๊ณ ๋ฆฌ๋ณ„ ์ง‘๊ณ„๊ฐ’์„ ์กฐ์ธํ•ด์ฃผ๊ณ  ์ง‘๊ณ„๊ฐ’์ด null๋กœ ์—†๋Š” ์นดํ…Œ๊ณ ๋ฆฌ ๋ฒ”์ฃผ๋Š” 0์ด ์ถœ๋ ฅ๋˜๋„๋ก IFNULL ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ–ˆ๋‹ค.

SELECT sal.category AS category,
       IFNULL(acc.cnt, 0) AS accounts_count
 FROM (
        SELECT 'High Salary' AS category
        UNION
        SELECT 'Average Salary' 
        UNION
        SELECT 'Low Salary'
        ) as sal
LEFT JOIN (
            SELECT  CASE WHEN income > 50000 THEN 'High Salary'
                         WHEN income BETWEEN 20000 AND 50000 THEN 'Average Salary'
                         ELSE 'Low Salary' END AS category
                        , COUNT(*) AS cnt
            FROM Accounts
            GROUP BY 1
            ) acc
ON sal.category = acc.category

'Growth ๐ŸŒณ > Practice ๐Ÿ’ป' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Leet code] 1393. Capital Gain/Loss  (1) 2023.10.04
[Leet code] 1204. Last Person to Fit in the Bus  (0) 2023.09.26
[Leet code] 1341. Movie Rating  (1) 2023.09.22
[Leet code] 1193. Monthly Transactions I  (0) 2023.09.21
[Leet code] 1174. Immediate Food Delivery II  (0) 2023.09.15