今天学习到了一个新的函数:group_concat
其使用方法:group_concat([distinct] 字段名 [order by 排序字段 asc/desc] [separator '分隔符'])
使用场景要求的输入输出如下:
输入:
Activities
表:
+------------+-------------+
| 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 |
+------------+-------------+
输出:
+------------+----------+------------------------------+
| sell_date | num_sold | products |
+------------+----------+------------------------------+
| 2020-05-30 | 3 | Basketball,Headphone,T-shirt |
| 2020-06-01 | 2 | Bible,Pencil |
| 2020-06-02 | 1 | Mask |
+------------+----------+------------------------------+
也就是先根据sell_date
进行分组group by
,根据分组的结果对products
进行group_concat
,并设置排序方式和间隔符号
给出解决以上场景的sql代码:
select sell_date,count(distinct product) as num_sold,
group_concat(distinct product order by product asc separator "," ) as products
from Activities
group by sell_date