SQL 알고리즘 코드카타

SQL 알고리즘 코드카타 20일차(1) 26.01.18(일)

nom_de_plume 2026. 1. 18. 21:11

부제:

년, 월, 성별 별 상품 구매 회원 수 구하기, 레벨 4

 

1. 문제 링크:https://school.programmers.co.kr/learn/courses/30/lessons/131532
2. 정답 코드: 

SELECT
    year(os.sales_date) as year,
    month(os.sales_date) as month,
    ui.gender,
    count(distinct os.user_id) as users
from user_info as ui
inner join online_sale as os
    on ui.user_id = os.user_id
where ui.gender is not null
group by year, month, ui.gender
order by 
    year asc, 
    month asc, 
    ui.gender asc


3. 오류 상황:

SELECT
    year(os.sales_date) as year,
    month(os.sales_date) as month,
    ui.gender
    count(os.user_id) as users
from user_info as ui
inner join online_sale as os
    on ui.user_id = os.user_id
where ui.gender is not null
order by 
    year asc, 
    month asc, 
    ui.gender asc

=> ','(쉼표) 누락

=> 중복 데이터 미처리

=> 그룹화 누락


4. 시도 방법:

=> ','(쉼표) 추가

=> DISTINCT 사용

=> GROUP BY 사용


5. 최종 문제 해결 방법:

=> SELECT 절의 ui.gender 뒤에 콤마(,)가 빠져 있어 문법 에러가 발생. ','(쉼표) 추가

=> 한 명의 회원이 같은 달에 상품을 여러 번 구매했을 경우, count(os.user_id)를 그대로 사용하면 구매 횟수만큼 숫자가 올라가게 된다. 우리는 '사람 수'를 세는 것이므로, 중복을 제거하고 집계할 수 있는 방법이 필요. DISTINCT 사용

=> SELECT 절에는 년, 월, 성별이 나열되어 있지만, 이 항목들로 데이터를 그룹화하는 GROUP BY 절이 빠져 있다. SQL에서 COUNT나 SUM 같은 집계 함수를 사용할 때는, 집계 기준이 되는 컬럼들을 반드시 묶어줘야 한다.