본문 바로가기
[업무 지식]/MySQL

[UNION] Count Salary Categories

by 에디터 윤슬 2024. 11. 7.
 

링크

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

 

문제

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.

The result format is in the following example.

정답

select 'Low Salary' as category,
        sum(case when income < 20000 then 1 else 0 end) as accounts_count
from accounts

union

select 'Average Salary' as category,
        sum(case when income between 20000 and 50000 then 1 else 0 end) as accounts_count
from accounts

union

select 'High Salary' as category,
        sum(case when income > 50000 then 1 else 0 end) as accounts_count
from accounts

해설

  • category 컬럼을 새로 생성: 원하는 '지정' 컬럼이 있다면 새로 생성
  • 원하는 값만 case when 구문으로 작성하여 해당하면 1, 해당하지 않으면 0을 입력해 합을 구함 

새롭게 이해한 내용

  • 없으면 만들면 된다