SQL - GROUP_CONCAT

 SELECT sell_date, count(DISTINCT product)as num_sold,

GROUP_CONCAT(DISTINCT product order by product) as products
FROM Activities
GROUP BY sell_date;


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.

Example – DISTINCT

You can use DISTINCT to remove duplicates (so that duplicate records become one record).

Example:

SELECT GROUP_CONCAT(DISTINCT TaskName) 
FROM Tasks;

Example – ORDER BY

You can use ORDER BY to order the results by a given column.

Example:

SELECT GROUP_CONCAT(DISTINCT TaskName ORDER BY TaskName DESC) 
FROM Tasks;

Example – Specify a Delimiter

By default, the list is a comma-separated list. However, you can specify a delimiter of your choice if required.

To do this, use SEPARATOR followed by the string literal value that should be inserted between group values.

Example:

SELECT GROUP_CONCAT(DISTINCT TaskName SEPARATOR ' + ') 
FROM Tasks;

Example:

SELECT GROUP_CONCAT(TaskId, ') ', TaskName SEPARATOR ' ') 
FROM Tasks;

留言

此網誌的熱門文章

MAP - Sort with stream

JAVA - DSF Example