表: Sales
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| sale_date | date |
| fruit | enum |
| sold_num | int |
+---------------+---------+
(sale_date, fruit) 是该表主键(具有唯一值的列的组合)。
该表包含了每一天中"苹果" 和 "桔子"的销售情况。
编写解决方案报告每一天 苹果 和 桔子 销售的数目的差异
返回的结果表, 按照格式为 (‘YYYY-MM-DD’) 的 sale_date
排序
输入:
Sales 表:
+------------+------------+-------------+
| sale_date | fruit | sold_num |
+------------+------------+-------------+
| 2020-05-01 | apples | 10 |
| 2020-05-01 | oranges | 8 |
| 2020-05-02 | apples | 15 |
| 2020-05-02 | oranges | 15 |
| 2020-05-03 | apples | 20 |
| 2020-05-03 | oranges | 0 |
| 2020-05-04 | apples | 15 |
| 2020-05-04 | oranges | 16 |
+------------+------------+-------------+
输出:
+------------+--------------+
| sale_date | diff |
+------------+--------------+
| 2020-05-01 | 2 |
| 2020-05-02 | 0 |
| 2020-05-03 | 20 |
| 2020-05-04 | -1 |
+------------+--------------+
解释:
sale_date
分组计算差值,需要计算 apples
和 oranges
的差值,可以将 fruit=oranges
的 sold_num
设置为负数,然后使用sum
实现计算差值select sale_date, sum(if(fruit = 'apples', sold_num, -sold_num)) as diff
from Sales
group by sale_date
order by sale_date;
执行结果
+----------+----+
|sale_date |diff|
+----------+----+
|2020-05-01|2 |
|2020-05-02|0 |
|2020-05-03|20 |
|2020-05-04|-1 |
+----------+----+