본문 바로가기
코딩테스트/SQL

[LeetCode][MySQL] Group Sold Products By The Date

by 포뇨j 2023. 12. 20.

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

 

Group Sold Products By The Date - LeetCode

Can you solve this real interview question? Group Sold Products By The Date - Table Activities: +-------------+---------+ | Column Name | Type | +-------------+---------+ | sell_date | date | | product | varchar | +-------------+---------+ There is no prim

leetcode.com

 

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_concat()이란 여러 레코드를 하나의 문자열로 합쳐서 반환하는 함수이다.

 

합치고자 하는 문자열 내의 순서를 정렬하고자 할 때는 다음과 같이 order by을 사용할 수 있다.

group_concat(distinct product order by product)

 

문자열 간의 구분자를 설정하고자 할 때는 separator로 구분자를 삽입하면 된다.

group_concat(distinct product separator ', ')