表 Activities:
±------------±--------+
| 列名 | 类型 |
±------------±--------+
| sell_date | date |
| product | varchar |
±------------±--------+
此表没有主键,它可能包含重复项。
此表的每一行都包含产品名称和在市场上销售的日期。
编写一个 SQL 查询来查找每个日期、销售的不同产品的数量及其名称。
每个日期的销售产品名称应按词典序排列。
返回按 sell_date 排序的结果表。
查询结果格式如下例所示。
±-----------±---------±-----------------------------+
| sell_date | num_sold | products |
±-----------±---------±-----------------------------+
| 2020-05-30 | 3 | Basketball,Headphone,T-shirt |
| 2020-06-01 | 2 | Bible,Pencil |
| 2020-06-02 | 1 | Mask |
±-----------±---------±-----------------------------+
难点:需要将查询出来的products使用’,'进行拼接
开始计划使用CONCAT_WS(symbol, str2, str3……)进行拼接,但是该函数需要使用已知的字段进行拼接,而本题使用的是查询的多行结果拼接
select
sell_date,
COUNT(distinct product ) as num_sold,
CONCAT_WS(',' , select product from Activities as b where b.sell_date = sell_date) as products
from
Activities as a
group by
sell_date
order by
sell_date;
报错
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘select product from Activities as b where b.sell_date = sell_date) as products
f’ at line 5
搜寻一番发现了GROUP_CONCAT函数
GROUP_CONCAT([DISTINCT] column1 [ORDER BY column2 ASC\DESC] [SEPARATOR seq]);
代码:
# Write your MySQL query statement below
select
sell_date,
COUNT(distinct product ) as num_sold,
GROUP_CONCAT(distinct product order by product SEPARATOR ',') products
from
Activities as a
group by
sell_date
order by
sell_date;