You're the manager of a fruit stand that sells only apples and oranges. Each day, you record the sales of both fruits in your database. Now you need to analyze your daily performance by calculating the net difference between apple and orange sales.
Given a Sales table with the following structure:
| Column Name | Type |
|---|---|
| sale_date | date |
| fruit | enum ('apples', 'oranges') |
| sold_num | int |
Where (sale_date, fruit) is the primary key, write a SQL query to calculate the difference between apples and oranges sold each day. The result should show apples_sold - oranges_sold for each date.
Goal: Return a table with sale_date and diff (positive if more apples sold, negative if more oranges sold), ordered by sale_date.
Input & Output
Visualization
Time & Space Complexity
Single pass through all records with GROUP BY operation, linear time complexity
Space proportional to number of unique dates (k), typically much smaller than total records (n)
Constraints
- 1 โค number of rows in Sales โค 1000
-
sale_dateis in format 'YYYY-MM-DD' -
fruitis either 'apples' or 'oranges' -
1 โค
sold_numโค 100 - Each (sale_date, fruit) combination appears at most once