[리트코드]|Group Sold Products By The Date; GROUP_CONCAT
https://leetcode.com/problems/group-sold-products-by-the-date/description/
1. Problem
날짜별로 판매된 서로 다른 제품의 개수와 제품 리스트를 구해야 한다. 제품 리스트는 알파벳 순으로 정렬되어야 하며, 중복된 제품명은 제거해야 한다. 행(Row)으로 나열된 데이터를 날짜라는 기준에 맞춰 하나의 열(Column)로 묶어내는 것이 핵심 과제이다.
2. Solution: 집계 함수와 문자열 통합
COUNT(DISTINCT)로 개수를 세고, GROUP_CONCAT을 이용해 문자열을 결합한다.
3. Takeaway: GROUP_CONCAT의 3대 핵심 옵션
- DISTINCT의 중요성: 동일한 날짜에 같은 제품이 여러 번 팔렸을 경우, DISTINCT가 없다면 리스트에 동일한 이름이 중복 노출된다. 개수(num_sold)와 리스트(products) 모두에 중복 제거를 적용하여 데이터의 신뢰도를 높였다.
- ORDER BY 내장: GROUP_CONCAT 내부에서 자체적으로 ORDER BY를 사용할 수 있다는 점은 매우 강력하다. 외부의 ORDER BY는 최종 결과 테이블의 순서를 정하지만, 함수 내부의 ORDER BY는 합쳐지는 문자열의 순서를 결정한다.
- 유연한 구분자(Separator): 기본값은 쉼표(,)이지만, 요구사항에 따라 SEPARATOR ' / '와 같이 변경하여 가독성을 조절할 수 있다.
Table Activities:
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| sell_date | date |
| product | varchar |
+-------------+---------+
There is no primary key (column with unique values) for this table. It may contain duplicates.
Each row of this table contains the product name and the date it was sold in a market.
Write a solution to find for each date the number of different products sold and their names.
The sold products names for each date should be sorted lexicographically.
Return the result table ordered by sell_date.
The result format is in the following example.
Example 1:
Input:
Activities table:
+------------+------------+
| sell_date | product |
+------------+------------+
| 2020-05-30 | Headphone |
| 2020-06-01 | Pencil |
| 2020-06-02 | Mask |
| 2020-05-30 | Basketball |
| 2020-06-01 | Bible |
| 2020-06-02 | Mask |
| 2020-05-30 | T-Shirt |
+------------+------------+
Output:
+------------+----------+------------------------------+
| sell_date | num_sold | products |
+------------+----------+------------------------------+
| 2020-05-30 | 3 | Basketball,Headphone,T-shirt |
| 2020-06-01 | 2 | Bible,Pencil |
| 2020-06-02 | 1 | Mask |
+------------+----------+------------------------------+
Explanation:
For 2020-05-30, Sold items were (Headphone, Basketball, T-shirt), we sort them lexicographically and separate them by a comma.
For 2020-06-01, Sold items were (Pencil, Bible), we sort them lexicographically and separate them by a comma.
For 2020-06-02, the Sold item is (Mask), we just return it.
1. 나의코드 = 정답코드!!!
SELECT sell_date,
COUNT(DISTINCT product) AS num_sold,
GROUP_CONCAT(DISTINCT product ORDER BY product ASC) as products
FROM Activities
GROUP BY sell_date
ORDER BY sell_date ASC;
GROUP_CONCAT 여러행의 문자열을 하나로 합칠 때 사용
GROUP_CONCAT(DISTINCT category ORDER BY category ASC)
- ORDER BY: 합쳐지는 순서를 정합니다.
- SEPARATOR: 기본값은 쉼표(,)이며, 원하는 구분자로 바꿀 수 있습니다.
- DISTINCT: 중복된 값이 있을 경우 하나만 표시하고 싶을 때 GROUP_CONCAT(DISTINCT 컬럼명) 형태로 씁니다.