+---------------+---------+
|Column Name |Type|+---------------+---------+
| sale_date | date || fruit | enum || sold_num | int |+---------------+---------+
(sale_date, fruit) is the primarykey (combination of columns withuniquevalues) of this table.
This tablecontains the sales of"apples"and"oranges" sold eachday.
Write a solution to report the difference between the number of apples and oranges sold each day.
Input:
Sales table:
+------------+------------+-------------+
| 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|+------------+------------+-------------+
Output:
+------------+--------------+
| sale_date | diff |+------------+--------------+
|2020-05-01|2||2020-05-02|0||2020-05-03|20||2020-05-04|-1|+------------+--------------+
Explanation:
Day2020-05-01, 10 apples and8 oranges were sold (Difference 10-8=2).
Day2020-05-02, 15 apples and15 oranges were sold (Difference 15-15=0).
Day2020-05-03, 20 apples and0 oranges were sold (Difference 20-0=20).
Day2020-05-04, 15 apples and16 oranges were sold (Difference 15-16=-1).
Intuition:
We need to find, for each day, the difference between apples and oranges sold. Since the data is in rows, we can use conditional aggregation to get the sum for each fruit per day, then subtract.
Approach:
Use GROUP BY sale_date to aggregate sales per day.
Use SUM(CASE WHEN fruit = 'apples' THEN sold_num ELSE 0 END) to get apples sold per day.
Use SUM(CASE WHEN fruit = 'oranges' THEN sold_num ELSE 0 END) to get oranges sold per day.
SELECT sale_date,
SUM(CASEWHEN fruit ='apples'THEN sold_num ELSE0END) -SUM(CASEWHEN fruit ='oranges'THEN sold_num ELSE0END) AS diff
FROM Sales
GROUPBY sale_date
ORDERBY sale_date;