리트코드(leetcode) 문제풀이 : Count Salary Categories (10/7)

백엔ㄷ현·2024년 10월 7일
0

Table: Accounts

Column NameType
account_idint
incomeint

account_id is the primary key (column with unique values) for this table.
Each row contains information about the monthly income for one bank account.

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.

Example 1:

Input:
Accounts table:

account_idincome
3108939
212747
887709
691796

Output:

categoryaccounts_count
Low Salary1
Average Salary0
High Salary3

Explanation:
Low Salary: Account 2.
Average Salary: No accounts.
High Salary: Accounts 3, 6, and 8.



급여의 범위에 해당하는 account_id 를 찾아서 범위별로 카테고리화 하는 문제
최근 문제들이 다 서브쿼리를 사용해서 풀었던 문제라 이번에도 서브쿼리로 접근을 하였다. 하지만 group by 로 해당하는 컬럼이 없는 Average Salary 를 조회하지 못하는 문제가 있었다.

-- 오답 쿼리
select category
    ,count(*) as accounts_count
from (
    select case
            when income < 20000 then 'Low Salary'
            when income between 20000 and 50000 then 'Average Salary'
            when income > 50000 then 'High Salary'
            end as category
    from accounts
) as salaries
group by category
order by category;

다른 방법으로 푼다는 생각을 못하고 계속 자잘한 부분만 고쳐가면서 문제를 풀었다.
다른 사람의 풀이들을 보고 아주 쉽게 풀 수 있다는 문제인걸 알았다. 아주 간단하게 풀 수 있는 문제를 아주 복잡하게 생각하느라 떠올리지 못하였다.

-- 정답 쿼리
select 'Low Salary' as category
    ,sum(income < 20000) as accounts_count
from accounts

union

select 'Average Salary' as category
        ,sum(income between 20000 and 50000) as accounts_count
from accounts

union

select 'High Salary' as category
        ,sum(income > 50000) as accounts_count
from accounts;

해당하는 범위의 급여 컬럼을 하나씩 조회하고 union 으로 테이블을 합치기만 하면 되는 간단? 한 문제였다.

profile
매일매일 공부한 내용과 코드 기록하겠습니다

0개의 댓글