~고군분투 인생살이~

[1484] Group Sold Products By The Date 본문

SQL/LEETCODE

[1484] Group Sold Products By The Date

소금깨 2022. 7. 12. 22:18

Table Activities:

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| sell_date   | date    |
| product     | varchar |
+-------------+---------+
There is no primary key 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 an SQL query 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 query 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.

 

문제 조건 

각 날짜에 판매된 product의 수와 product의 이름을 출력하시오.

판매된 제품의 이름은 사전순으로 정렬되어야 합니다

출력되는 테이블의 값들은 sell_date로 정렬되어야 합니다.

 

풀이 과정 

조건 1에 부합하기 위해서 sell_date로 group by를 해줌    - product의 수는 count를 사용해서 집계    - product의 이름은 group_concat을 이용해 붙여주기 조건 2를 만족하기 위해 group_concat에 order by를 추가로 이용하여 product를 asc로 정렬한다조건 3을 만족하기 위해 전체 테이블에 order by절을 이용해서 sell_date ASC로 정렬한다 

SELECT sell_date
		, COUNT(DISTINCT product) AS num_sold --조건 1 
        , GROUP_CONCAT(DISTINCT product ORDER BY product) AS products -- 조건 1 / 조건 2 
from Activities 
GROUP BY sell_date -- 날짜 별로 그룹화 하기 
ORDER BY sell_date -- 조건 3

GROUP_CONCAT?

- 특정컬럼의 각 결과값을 하나의 가로열로 표현하는 함수 

# 컬럼 값들을 가로로 연결하기 
SELECT GROUP_CONCAT(name) FROM employees

King,Amanda,Silvia...

# 컬럼 값들을 연결 시 구분자를 지정해 줄수있다. 
SELECT GROUP_CONCAT(name separator '|') FROM employees 

King|Amanda|Silvia...

# 컬럼 값들에 대해 정렬을 지정해 줄 수 있다.
SELECT GROUP_CONCAT(name order by department_id DESC) FROM employees 

Amanda|Silvia|King...

# 컬럼 값들에 대해 중복값 제거 및 정렬 순서 추가해서 연결하기
SELECT GROUP_CONCAT(DISTINCT(department_id) order by name) FROM employees

Silvia,King,Amanda...

 

 

 

Comments