코딩테스트/SQL 코딩테스트

<LeetCode> Group Sold Products By The Date

배또가또 2024. 4. 10. 12:49

출처 :  https://leetcode.com/problems/group-sold-products-by-the-date/description/


  •  문제요구사항
    • 날짜 별로 판매된 다양한 제품의 수와 이름을 찾는 쿼리를 작성
      • ex) 2020-05-30, 3, Basketball, Headphone, T-shirt
      • 위 처럼 해당하는 날짜의 제품 이름이 한 개의 컬럼에 표시되도록 해야함
    • 각 날짜에 판매된 제품 이름은 사전순으로 정렬

정답코드

MySQL

select sell_date, 
       count(distinct product) as num_sold, 
       group_concat(distinct product order by product) as products
from activities
group by sell_date
order by sell_date;

 

group_concat 함수를 사용하면 group by 컬럼을 기준으로 해당 하는 컬럼의 행을 합칠 수 있으며

separator를 통해서 구분자 또한 설정할 수 있다.

 

ex) select type, group_concat(name separator '|') from test group by type

 

구분자를 설정하지 않으면 자동으로 ,(콤마)가 구분자가 되며 order by를 통해서 합칠 순서도 설정할 수 있다.

 

참고링크 : https://fruitdev.tistory.com/16#google_vignette

 

[MySQL] GROUP_CONCAT 사용하기

필요에 의해 서로 다른 결과를 한줄로 합쳐서 보여줘야 할 경우가 있다. 전체 결과값을 가져와서 java 와 같은 프로그램 언어에서 for 문을 돌며 문자열을 붙여도 되긴 하지만 Select 쿼리를 던질때

fruitdev.tistory.com