SQL 알고리즘 코드카타

SQL 알고리즘 코드카타 23일차(1) 26.01.21(수)

nom_de_plume 2026. 1. 21. 09:33

부제:

오프라인/온라인 판매 데이 통합하기, 레벨 5

 

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

SELECT
    date_format(sales_date, "%Y-%m-%d") as sales_date,
    product_id,
    user_id,
    sales_amount
from online_sale
where sales_date like "2022-03%"
union all
select
    date_format(sales_date, "%Y-%m-%d") as sales_date,
    product_id,
    null as user_id,
    sales_amount
from offline_sale
where sales_date like "2022-03%"
order by 
    sales_date asc, 
    product_id asc, 
    user_id asc


3. 오류 상황:

SELECT
    os.sales_date,
    os.product_id,
    os.user_id,
    os.sales_amount
from online_sale as os
join offline_sale as ofs
    on os.product_id = ofs.product_id
where (os.sales_date, ofs.sales_date) in (
    select
        os.sales_date,
        ofs.sales_date,
        (os.sales_date+ofs.sales_date) as sales_date
    from offline_sale as ofs
    where (os.sales_date+ofs.sales_date) between "2022-03-01" and "2022-03-31"
    order by (os.sales_date+ofs.sales_date)
)
order by 
    sales_date asc, 
    product_id asc, 
    user_id asc

=> JOIN 오용

=> WHERE 절 오류

=> 오프라인 테이블 상품ID 미처리


4. 시도 방법:

=> UNION ALL 사용

=> WHERE 절 수정

=> 오프라인 테이블 상품ID  NULL 처리


5. 최종 문제 해결 방법:

=> JOIN은 두 테이블을 옆으로 붙이는 것이고, UNION ALL은 두 테이블의 결과를 위아래로 합치는 것입니다. 문제에서 "온라인 데이터와 오프라인 데이터를 모두 출력"하라고 했으므로, 두 테이블의 형식을 맞춰서 합쳐야한다. 

=> 오프라인 테이블에는 USER_ID가 없습니다. 문제의 요구대로 이 자리에 NULL AS USER_ID 로 명시

=> WHERE절에  각각의 SELECT 문 안에 2022년 3월 데이터를 필터링하는 조건 추가

=> 두 테이블을 합친 최종 결과물에 대해 정렬해야 하므로, 쿼리의 맨 마지막에 한 번만 작성