[SQL문제풀기] 카테고리 별 상품 개수 구하기(GROUP BY)

241122
이나겸's avatar
Nov 21, 2024
[SQL문제풀기] 카테고리 별 상품 개수 구하기(GROUP BY)

Q. PRODUCT 테이블에서 상품 카테고리 코드(PRODUCT_CODE 앞 2자리) 별 상품 개수를 출력하는 SQL문을 작성해주세요. 결과는 상품 카테고리 코드를 기준으로 오름차순 정렬해주세요.

 
 

풀이

  • substring : 문자열의 시작 위치와 길이를 지정하여 부분 문자열을 추출
    • substring(product_code, 1, 2) : product_code의 앞 두 자리 추출
  • group by : 그룹화
select substring(product_code, 1, 2) as category, count(*) as products from product group by substring(product_code, 1, 2) order by product_code asc;
Share article

Nakyeom's Study