The Stocks table logs buy and sell operations on stocks. For each stock and each calendar month in which that stock had at least one operation, report the net share count. Shares sold count as positive and shares bought count as negative, so a month with more buying than selling has a negative result.
Input Table(s)
Stocks
| Column | Type | Meaning |
|---|
| stock_name | VARCHAR(50) | Name of the stock (not null) |
| operation | ENUM ('Buy', 'Sell') | Whether shares were bought or sold (not null) |
| operation_day | DATE | Date of the operation (not null) |
| shares_count | INT | Number of shares in the operation (not null, positive) |
The table has no primary key and may contain duplicate rows.
Output Contract
One row per (stock_name, month) pair that has at least one operation, with these columns in this order:
| Column | Type | Meaning |
|---|
| stock_name | VARCHAR | The stock |
| month | TEXT | Year and month of operation_day, formatted YYYY-MM (for example 2021-06) |
| share_count | BIGINT | Sum of shares_count over the stock's operations in that month, with Sell rows added and Buy rows subtracted |
Order by month ascending, then stock_name ascending. Each (month, stock_name) pair appears once, so this ordering is unique. Note that the output column is share_count, while the input column is shares_count.
Example
Input Stocks:
| stock_name | operation | operation_day | shares_count |
|---|
| ABC | Buy | 2021-06-01 | 10 |
| ABC | Buy | 2021-06-15 | 20 |
| ABC | Sell | 2021-06-20 | 5 |
| XYZ | Sell | 2021-06-10 | 100 |
Expected output:
| stock_name | month | share_count |
|---|
| ABC | 2021-06 | -25 |
| XYZ | 2021-06 | 100 |
In June 2021, ABC had two buys (10 + 20 = 30 subtracted) and one sell (5 added), so its share count is -30 + 5 = -25. XYZ had one sell of 100 shares, so its share count is 100. Both rows are in the same month, so stock_name decides the order.
Constraints and Clarifications
-
The table has at least one row.
-
No column is NULL,
operation
is always exactly
'Buy'
or
'Sell'
, and
shares_count
is a positive integer.
-
Each row is one operation. Duplicate rows are separate operations that happen to match, and every one of them counts toward the total.
-
A month is a calendar month of a specific year: June 2021 and June 2022 are different rows.
-
A stock-month whose buys and sells cancel out still appears, with a
share_count
of 0.
-
Stock-months with no operations are omitted. Do not add zero rows for them.