SQL 과제: 언제 사례를 사용하여 소득별로 고객을 그룹화할 수 있습니까?
SQL Challenge: Can You Group Customers by Income Using CASE WHEN?
고객 ID, 이름 및 연간 소득이 포함된 고객 테이블이 있습니다.
핵심 요약
자동 요약- 1고객 ID, 이름 및 연간 소득이 포함된 고객 테이블이 있습니다.
- 2비즈니스 팀은 각 소득 범주에 속하는 고객의 수를 파악하고자 합니다.
- 3카테고리는 다음과 같습니다: 저소득: ₹ 3,00,000 이하 중간 소득: ₹ 3,00,000 ~ ₹ 7,00,000 고소득: ₹ 7,00,000 이상 SQL을…
원문 본문
출처 · dev.to
Here is a practical problem you might face while preparing a customer analysis report.
You have a customers table containing customer IDs, names and annual income.
The business team wants to understand how many customers fall into each income category.
The categories are:
- Low Income: Below ₹3,00,000
- Middle Income: ₹3,00,000 to ₹7,00,000
- High Income: Above ₹7,00,000
How would you create this report using SQL?
customers
customer_id | name | annual_income
101 | Rahul | 250000
102 | Priya | 450000
103 | Amit | 850000
104 | Sneha | 300000
105 | Karan | 650000
106 | Neha | 950000
107 | Rohan | 200000
Your Challenge
Write a query to:
- Categorize customers using CASE WHEN.
- Count the number of customers in each category.
- Display the income category along with the total customer count.
- Do not change the original table data.
Think before you scroll!
The SQL Solution (Oracle)
SELECT
CASE
WHEN annual_income < 300000
THEN 'Low Income'
WHEN annual_income <= 700000
THEN 'Middle Income'
ELSE 'High Income'
END AS income_category,
COUNT(*) AS total_customers
FROM customers
GROUP BY
CASE
WHEN annual_income < 300000
THEN 'Low Income'
WHEN annual_income <= 700000
THEN 'Middle Income'
ELSE 'High Income'
END;
Expected Output
income_category | total_customers
Low Income | 2
Middle Income | 3
High Income | 2
Why Does This Work?
CASE WHEN checks the annual income of each customer and assigns an income category.
Customers earning below ₹3,00,000 are placed in Low Income.
Customers earning from ₹3,00,000 to ₹7,00,000 are placed in Middle Income.
All remaining customers are placed in High Income.
GROUP BY combines customers belonging to the same category.
COUNT(*) calculates how many customers belong to each group.
That's it. CASE WHEN and GROUP BY help convert individual customer records into a useful business report.
One Thing to Remember:
The order of conditions in CASE WHEN matters.
Once a condition is satisfied, SQL returns its corresponding result without checking the remaining conditions.
Your Turn
Suppose you want to display the actual customer names along with their income categories instead of just counting customers.
How would you modify this query?
Share your SQL query in the comments!
SQL #SQLChallenge #OracleSQL #DataAnalytics #LearnSQL
이 글은 dev.to 의 원문을 정제해 보여드립니다. 저작권은 원저작자에게 있습니다.
전체 내용이 궁금하다면
dev.to 원문에서 이어 읽기




