코드카타/SQL, Pandas
112. Count Salary Categories
susinlee
2025. 1. 16. 09:38
[문제]
https://leetcode.com/problems/count-salary-categories/description/
[풀이]
1. category의 모든 범주를 가져와야 하므로 참조테이블을 만든다.
2. 각 범주에 해당하는 조건으로 행을 필터링하고 행의 개수를 세어준다.
3. 아래 코드는 1, 2 번을 동시에 하는 방법이다
Pandas
import pandas as pd
def count_salary_categories(accounts: pd.DataFrame) -> pd.DataFrame:
return pd.DataFrame({
'category': ['Low Salary', 'Average Salary', 'High Salary'],
'accounts_count': [
accounts[accounts.income < 20000].shape[0],
accounts[(accounts.income >= 20000) & (accounts.income <= 50000)].shape[0],
accounts[accounts.income > 50000].shape[0]
]
})
SQL
SELECT
'Low Salary' AS category
, (SELECT COUNT(*) FROM Accounts WHERE income < 20000) AS accounts_count
UNION ALL
SELECT
'Average Salary'
, (SELECT COUNT(*) FROM Accounts WHERE income >= 20000 AND income <= 50000)
UNION ALL
SELECT
'High Salary'
, (SELECT COUNT(*) FROM Accounts WHERE income > 50000)
[