SQL

코테 준비 | Group Sold Products By The Date(group_concat)

성장하는 쿠키의 로그 기록 2025. 1. 15. 10:13

☑️  1484. Group Sold Products By The Date

[문제]

  • Write a solution to find for each date the number of different products sold and their names.Return the result table ordered by sell_date.
  • The sold products names for each date should be sorted lexicographically.
  • 날짜별 팔린 제품 갯수 집계 및 팔린 제품명 한 컬럼에 기재 

[문제 풀이]

내 코드 → 끝까지 못 품 (실패)

WITH rownt AS (
SELECT sell_date
      ,product 
      ,ROW_NUMBER() OVER (PARTITION BY sell_date ORDER BY product ) AS rown
FROM activities 
GROUP BY sell_date,product 
),conct AS (
    SELECT sell_date
        ,COUNT(DISTINCT product) AS num_sold
        ,MAX(IF(rown=1,product,0)) as fir
        ,MAX(IF(rown=2,product,0)) as sec
        ,MAX(IF(rown=3,product,0)) as thir
    FROM rownt
    GROUP BY sell_date
    ORDER BY sell_date
)
SELECT sell_date
        ,num_sold
        ,CASE WHEN num_sold=3 THEN CONCAT(fir,',',sec,',',thir) 
              WHEN num_sold=2 THEN CONCAT(fir,',',sec)
              ELSE fir 
        END as products -- 문제는 문자열이 몇개 있을지 몰라 
FROM conct
ORDER BY sell_date

 

수정 코드 → 정답

SELECT sell_date
     ,COUNT(DISTINCT product) AS num_sold
     ,GROUP_CONCAT(DISTINCT product ORDER BY product SEPARATOR ',') AS products
FROM activities
GROUP BY sell_date

 

이슈 및 해결 과정

  • 아이디어(GROUP_CONCAT 함수 존재를 몰랐음) : 날짜별 제품 넘버링 후 피벗 돌려 CONCAT 해준다
    • `rownt` CTE : 윈도우 함수로 넘버링
    • `conct` CTE : 순서별 피벗팅
    • 아우터 쿼리 : 집계 갯수 조건별 concat 
    • → 문제상황) 갯수가 제한되지 않았기 때문에 조건문을 몇개를 걸어야 할지 모름 
    • → 실패
  • 해결 
    • MYSQL DOCS 확인 후 그룹내 NULL 이 아닌 값(문자열)을 연결해주는 함수가 따로 있음
    • `GROUP_CONCAT' 함수 사용하여 간단하게 해결 
  • `GROUP_CONCAT` ? (하단 mysql docs 참고)
    • 그룹내 NULL 이 아닌 값(문자열)을 연결
    • 파라미터 옵션 : DISCINT (중복제외 ), ORDER BY (연결 순서 지정), SEPARATOR '구분문자' 
  • 복습 사항
    • NULL 포함 `CONCAT` 시 최종 NULL 로 반환
    • 혼합타입에서 MAX 값 순서 : 문자형 → 숫자형 (EX. MAX('ABC' , 0) 이라면 'ABC' 반환) 

 

한줄 포인트

  • GROUP_CONCAT 함수를 새로 알았음. 문자열 연결시 유용하게 사용할듯
  • NULL 포함 CONCAT 값의 최종 반환값은 NULL 임
  • MAX 인자로 문자형과 숫자형이 있을때 문자형이 최대값임 , NULL 은 집계시 무시됨 
 

MySQL :: MySQL 8.4 Reference Manual :: 14.19.1 Aggregate Function Descriptions

MySQL 8.4 Reference Manual  /  ...  /  Functions and Operators  /  Aggregate Functions  /  Aggregate Function Descriptions 14.19.1 Aggregate Function Descriptions This section describes aggregate functions that operate on sets of values. They are

dev.mysql.com