当前位置:网站首页>Database daily question - day 20: selling products by date

Database daily question - day 20: selling products by date

2022-06-22 23:52:00 InfoQ


One 、 Problem description

surface
 
Activities

+-------------+---------+
|  Name  |  type  |
+-------------+---------+
| sell_date | date |
| product | varchar |
+-------------+---------+
This table has no primary key , It may contain duplicates .
Each row of this table contains the product name and the date of sale in the market .

Write a  
SQL
  Query to find each
date
、 Selling different products
Quantity and name
. The name of the product sold on each date shall be in accordance with
Dictionary order
array . Back to press  
sell_date
  Sorted result table .

Query results
The format is shown in the following example .

Topic link
Sell products by date

Two 、 Subject requirements

Examples

Input :
Activities  surface :
+------------+-------------+
| 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 |
+------------+----------+------------------------------+
explain :
about 2020-05-30, The items for sale are  (Headphone, Basketball, T-shirt), Arrange in dictionary order , And use commas  ','  Separate .
about 2020-06-01, The items for sale are  (Pencil, Bible), Arrange in dictionary order , Separated by a comma .
about 2020-06-02, The items for sale are  (Mask), Just return the item name .

Investigate

1. Aggregate functions 、 logic analysis
2. It is recommended to use time 10~25min

3、 ... and 、 Problem analysis

This question mainly examines
Aggregate analysis
and
Sorting function
, The question asks us to work out the daily sales
Different products
The quantity and name of , Note that the data of the subject may be unique , We're going to do the data
The only change
Handle .

Everything else is easy , Just group the dates , But we have to input the name of each product , This is a little difficult . We can look at a function
group_concat
A certain field after grouping is divided into
,
Splicing is OK .

Four 、 coded

select sell_date,count(distinct product) as 'num_sold',
group_concat(distinct product order by product separator ',') as 'products'
from Activities
group by sell_date
order by sell_date 

5、 ... and 、 test result

null
null
null
原网站

版权声明
本文为[InfoQ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206222132521156.html