题目:
表 Activities:
±------------±--------+
| 列名 | 类型 |
±------------±--------+
| sell_date | date |
| product | varchar |
±------------±--------+
此表没有主键,它可能包含重复项。
此表的每一行都包含产品名称和在市场上销售的日期。
编写一个 SQL 查询来查找每个日期、销售的不同产品的数量及其名称。
每个日期的销售产品名称应按词典序排列。
返回按 sell_date 排序的结果表。
查询结果格式如下例所示。
输入:
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 |
±-----------±---------±-----------------------------+
解答:
select sell_date, count(distinct sell_date,product) as num_sold ,group_concat(distinct product) as products
from Activities
group by sell_date
知识点:
distinct位置: 单独的distinct只能放在开头,否则报错,语法错误,与其他函数使用时候,没有位置限制
distinct用法:
a.在count计算不重复的记录的时候能用到
b.在需要返回记录不同的id的具体值的时候可以用
c.上面的情况2对于需要返回mysql表中2列以上的结果时会有歧义
比如SELECT DISTINCT player_id, task_id FROM task;
实际上返回的是player_id与task_id同时不相同的结果,也就是DISTINCT同时作用了两个字段,必须得player_id与task_id都相同的才被排除了,与我们期望的结果不一样,我们期望的是player_id不同被过滤
在这种情况下,distinct同时作用了两个字段,player_id,task_id
concat()用法:
功能:将多个字符串连接成一个字符串
这里注意:并且每个字符串不能为空,否则返回null
参数格式:
concat(str1,separator,str2,....) 用分隔符拼接,多个字段需写多个分隔符
concat(str1,str2,....) 直接拼接
concat_ws(separator,str1,str2,.....)
group_concat(distinct str1)