2021-04-01

大厂面试题(数据库)——格式化产品名称

写一个 SQL 语句报告:

product_name 是小写字母且不包含前后空格

sale_date 格式为 (‘YYYY-MM’)

total 是产品在本月销售的次数

返回结果以 product_name 升序 排列,如果有排名相同, 再以 sale_date 升序 排列。

+--------------+--------------+----------+
| product_name | sale_date    | total    |
+--------------+--------------+----------+
| lcphone      | 2000-01      | 2        |
| lckeychain   | 2000-02      | 2        | 
| lcphone      | 2000-02      | 1        | 
| matryoshka   | 2000-03      | 1        | 
+--------------+--------------+----------+

In January, 2 LcPhones were sold, please note that the product names are not case sensitive and may contain spaces.
In Februery, 2 LCKeychains and 1 LCPhone were sold.
In March, 1 matryoshka was sold.
Create table If Not Exists 103_Sales (sale_id int, product_name varchar(30), sale_date date);
Truncate table 103_Sales;
insert into 103_Sales (sale_id, product_name, sale_date) values ('1', 'LCPHONE', '2000-01-16');
insert into 103_Sales (sale_id, product_name, sale_date) values ('2', 'LCPhone', '2000-01-17');
insert into 103_Sales (sale_id, product_name, sale_date) values ('3', 'LcPhOnE', '2000-02-18');
insert into 103_Sales (sale_id, product_name, sale_date) values ('4', 'LCKeyCHAiN', '2000-02-19');
insert into 103_Sales (sale_id, product_name, sale_date) values ('5', 'LCKeyChain', '2000-02-28');
insert into 103_Sales (sale_id, product_name, sale_date) values ('6', 'Matryoshka', '2000-03-31');

最终SQL:

select 
     trim(lower(product_name)) as product_name, 
     date_format(sale_date,'%Y-%m') as sale_date,
     count(*) as total 
from 
     103_Sales 
group by
     trim(lower(product_name)),
     date_format(sale_date,'%Y-%m') 
order by
     product_name asc, 
     sale_date asc;
上一篇:要变强,不空喊,ak题目,继续向前。(背包DP优化+bitset应用)


下一篇:活动调度