azarasi / LeetCode 1445. Apples & Oranges

Created Thu, 14 Apr 2022 14:08:45 +0800 Modified Wed, 18 Sep 2024 14:00:22 +0000

Table: Sales

Column NameType
sale_datedate
fruitenum
sold_numint

(sale_date, fruit) is the primary key for this table. This table contains the sales of “apples” and “oranges” sold each day.

Write an SQL query to report the difference between the number of apples and oranges sold each day.

Return the result table ordered by sale_date.

The query result format is in the following example.

Example 1:

Input: Sales table:

sale_datefruitsold_num
2020-05-01apples10
2020-05-01oranges8
2020-05-02apples15
2020-05-02oranges15
2020-05-03apples20
2020-05-03oranges0
2020-05-04apples15
2020-05-04oranges16

Output:

sale_datediff
2020-05-012
2020-05-020
2020-05-0320
2020-05-04-1

Explanation: Day 2020-05-01, 10 apples and 8 oranges were sold (Difference 10 - 8 = 2). Day 2020-05-02, 15 apples and 15 oranges were sold (Difference 15 - 15 = 0). Day 2020-05-03, 20 apples and 0 oranges were sold (Difference 20 - 0 = 20). Day 2020-05-04, 15 apples and 16 oranges were sold (Difference 15 - 16 = -1).

SELECT sale_date,
       SUM(
               CASE
                   WHEN fruit = 'apples' THEN sold_num
                   ELSE - sold_num
                   END
           ) AS diff
FROM Sales
GROUP BY sale_date
ORDER BY sale_date;