1
+ -- Question 116
2
+ -- Table Activities:
3
+
4
+ -- +-------------+---------+
5
+ -- | Column Name | Type |
6
+ -- +-------------+---------+
7
+ -- | sell_date | date |
8
+ -- | product | varchar |
9
+ -- +-------------+---------+
10
+ -- There is no primary key for this table, it may contains duplicates.
11
+ -- Each row of this table contains the product name and the date it was sold in a market.
12
+
13
+
14
+ -- Write an SQL query to find for each date, the number of distinct products sold and their names.
15
+
16
+ -- The sold-products names for each date should be sorted lexicographically.
17
+
18
+ -- Return the result table ordered by sell_date.
19
+
20
+ -- The query result format is in the following example.
21
+
22
+ -- Activities table:
23
+ -- +------------+-------------+
24
+ -- | sell_date | product |
25
+ -- +------------+-------------+
26
+ -- | 2020-05-30 | Headphone |
27
+ -- | 2020-06-01 | Pencil |
28
+ -- | 2020-06-02 | Mask |
29
+ -- | 2020-05-30 | Basketball |
30
+ -- | 2020-06-01 | Bible |
31
+ -- | 2020-06-02 | Mask |
32
+ -- | 2020-05-30 | T-Shirt |
33
+ -- +------------+-------------+
34
+
35
+ -- Result table:
36
+ -- +------------+----------+------------------------------+
37
+ -- | sell_date | num_sold | products |
38
+ -- +------------+----------+------------------------------+
39
+ -- | 2020-05-30 | 3 | Basketball,Headphone,T-shirt |
40
+ -- | 2020-06-01 | 2 | Bible,Pencil |
41
+ -- | 2020-06-02 | 1 | Mask |
42
+ -- +------------+----------+------------------------------+
43
+ -- For 2020-05-30, Sold items were (Headphone, Basketball, T-shirt), we sort them lexicographically and separate them by comma.
44
+ -- For 2020-06-01, Sold items were (Pencil, Bible), we sort them lexicographically and separate them by comma.
45
+ -- For 2020-06-02, Sold item is (Mask), we just return it.
46
+
47
+ -- Solution
48
+ select sell_date, count (distinct product) as num_sold, group_concat(distinct product) as products
49
+ from activities
50
+ group by 1
51
+ order by 1
0 commit comments