|
| 1 | +Table: Sales |
| 2 | + |
| 3 | ++--------------+---------+ |
| 4 | +| Column Name | Type | |
| 5 | ++--------------+---------+ |
| 6 | +| sale_id | int | |
| 7 | +| product_name | varchar | |
| 8 | +| sale_date | date | |
| 9 | ++--------------+---------+ |
| 10 | +sale_id is the primary key for this table. |
| 11 | +Each row of this table contains the product name and the date it was sold. |
| 12 | + |
| 13 | + |
| 14 | +Since table Sales was filled manually in the year 2000, product_name may contain leading and/or trailing white spaces, also they are case-insensitive. |
| 15 | + |
| 16 | +Write an SQL query to report |
| 17 | + |
| 18 | +product_name in lowercase without leading or trailing white spaces. |
| 19 | +sale_date in the format ('YYYY-MM'). |
| 20 | +total the number of times the product was sold in this month. |
| 21 | +Return the result table ordered by product_name in ascending order. In case of a tie, order it by sale_date in ascending order. |
| 22 | + |
| 23 | +The query result format is in the following example. |
| 24 | + |
| 25 | + |
| 26 | + |
| 27 | +Example 1: |
| 28 | + |
| 29 | +Input: |
| 30 | +Sales table: |
| 31 | ++---------+--------------+------------+ |
| 32 | +| sale_id | product_name | sale_date | |
| 33 | ++---------+--------------+------------+ |
| 34 | +| 1 | LCPHONE | 2000-01-16 | |
| 35 | +| 2 | LCPhone | 2000-01-17 | |
| 36 | +| 3 | LcPhOnE | 2000-02-18 | |
| 37 | +| 4 | LCKeyCHAiN | 2000-02-19 | |
| 38 | +| 5 | LCKeyChain | 2000-02-28 | |
| 39 | +| 6 | Matryoshka | 2000-03-31 | |
| 40 | ++---------+--------------+------------+ |
| 41 | +Output: |
| 42 | ++--------------+-----------+-------+ |
| 43 | +| product_name | sale_date | total | |
| 44 | ++--------------+-----------+-------+ |
| 45 | +| lckeychain | 2000-02 | 2 | |
| 46 | +| lcphone | 2000-01 | 2 | |
| 47 | +| lcphone | 2000-02 | 1 | |
| 48 | +| matryoshka | 2000-03 | 1 | |
| 49 | ++--------------+-----------+-------+ |
| 50 | +Explanation: |
| 51 | +In January, 2 LcPhones were sold. Please note that the product names are not case sensitive and may contain spaces. |
| 52 | +In February, 2 LCKeychains and 1 LCPhone were sold. |
| 53 | +In March, one matryoshka was sold. |
| 54 | + |
| 55 | + |
| 56 | + |
| 57 | +# Write your MySQL query statement below |
| 58 | +select trim(lower(product_name)) as product_name, |
| 59 | + date_format(sale_date,'%Y-%m') as sale_date, |
| 60 | + count(product_name) as total |
| 61 | +from Sales |
| 62 | +group by trim(lower(product_name)),date_format(sale_date,'%Y-%m') |
| 63 | +order by trim(lower(product_name)),date_format(sale_date,'%Y-%m') |
0 commit comments