The transactions table holds one row per transaction a merchant received. Using window functions, compute each merchant's monthly revenue and running cumulative revenue. Return merchant_id, month (YYYY-MM), monthly_revenue (sum of amounts that month), and cumulative_revenue (running total of monthly revenue per merchant, ordered by month). Order by merchant_id, then month, both ascending.
Input Table(s)
transactions
| Column | Type | Meaning |
|---|
id | INTEGER | Primary key, one row per transaction |
merchant_id | INTEGER | Merchant that received the transaction, NOT NULL |
amount | NUMERIC(10,2) | Transaction amount, NOT NULL |
transaction_date | TIMESTAMP | When the transaction happened, NOT NULL |
Primary key: id.
Output Contract
| Column | Type | Meaning |
|---|
merchant_id | INTEGER | The merchant |
month | TEXT | Calendar month of transaction_date, formatted YYYY-MM |
monthly_revenue | NUMERIC | Sum of amount for that merchant in that month |
cumulative_revenue | NUMERIC | Sum of monthly_revenue over that merchant's months up to and including this one |
Return one row per (merchant_id, month) pair that has at least one transaction. Order by merchant_id ascending, then month ascending. The pair is unique, so the order is fully determined. No rounding is needed: amounts have two decimal places and the sums keep them exactly.
Example
transactions
| id | merchant_id | amount | transaction_date |
|---|
| 1 | 1 | 100.00 | 2024-01-05 10:00:00 |
| 2 | 1 | 50.00 | 2024-01-20 14:30:00 |
| 3 | 2 | 40.00 | 2023-12-15 08:00:00 |
| 4 | 2 | 75.50 | 2024-02-10 11:00:00 |
| 5 | 1 | 200.00 | 2024-03-02 09:15:00 |
| 6 | 2 | 24.50 | 2024-02-28 23:59:59 |
| 7 | 2 | 10.00 | 2024-03-01 00:00:00 |
| 8 | 1 | 30.00 | 2024-03-31 23:59:59 |
Expected result:
| merchant_id | month | monthly_revenue | cumulative_revenue |
|---|
| 1 | 2024-01 | 150.00 | 150.00 |
| 1 | 2024-03 | 230.00 | 380.00 |
| 2 | 2023-12 | 40.00 | 40.00 |
| 2 | 2024-02 | 100.00 | 140.00 |
| 2 | 2024-03 | 10.00 | 150.00 |
Merchant 1 has no transactions in February 2024, so that month does not appear and the March running total continues from January (150.00 + 230.00). Merchant 2 starts in December 2023, which sorts before 2024-02 because months are compared in calendar order.
Constraints and Clarifications
-
The table has 1 to 10,000 rows.
-
amount
is positive and
merchant_id
is a positive integer. No column can be NULL.
-
A month appears for a merchant only when that merchant has at least one transaction in it. Empty months are not filled in.
-
The month comes from the stored
transaction_date
value with no time zone conversion, so
2024-03-31 23:59:59
belongs to
2024-03
.
-
Several transactions for the same merchant in the same month are added into a single row, including transactions with identical timestamps.