SQL 알고리즘 코드카타

SQL 알고리즘 코드카타 17일차(2) 26.01.15(목)

nom_de_plume 2026. 1. 15. 10:16

부제:

5월 식품들의 총매출 조회하기, 레벨 3

 

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

SELECT
    fp.product_id,
    fp.product_name,
    sum(fp.price * fo.amount) as total_sales
from food_product as fp
inner join food_order as fo
    on fp.product_id = fo.product_id
where fo.produce_date like ('2022-05-%')
group by fp.product_id, fp.product_name
order by 
    total_sales desc,
    fp.product_id asc;


3. 오류 상황:

SELECT
    fp.product_id,
    fp.product_name,
    fp.price * fo.amount as total_sales
from food_product as fp
inner join food_order as fo
    on fp.product_id = fo.product_id
where fo.in_date like ('2022-05-%')
order by total_sales asc;

=> 총매출 계산 sum() 함수 누락

=> group by 기준 컬럼 오류

=> where 필터링 기준 컬럼 오류

 

4. 시도 방법:

=> sum() 집계함수 사용

=> group by 컬럼 수정

=> where 필터링 기준 컬럼 수정


5. 최종 문제 해결 방법:

=> 각 주문 한 건당의 매출 계산에서 집계함수 sum()을 사용해 총매출 계산

=> 비집계 컬럼 모두 group by에 포함

=> 입고일이 아닌 생산일 기준으로 구분해야 하기때문에 생산일 컬럼 where문에 포함