Monthly Expense Change
0:00:00
Let’s say we work at Janssen and track expense charges, one row per charge. Write a query that returns, for every user and month, their total expenses that month and the change from their previous month with charges.
The expenses table has the following columns:
| Column | Type |
|---|---|
id |
INTEGER |
user_id |
INTEGER |
charged_at |
DATETIME |
amount |
FLOAT |
Rules:
- Group months by calendar year and month, formatted as YYYY-MM in the month column.
- expense_diff is the current month’s total minus the total of the user’s most recent earlier month that has any charges (months with no charges are skipped and do not appear in the output); the earliest month per user has a NULL difference but still appears if the user has more than one month overall.
- Exclude any user who has expenses in only one distinct month.
- Sort by user_id ascending, then by month ascending.
Example:
Input:
expenses table
| Column | Type |
|---|---|
id |
INTEGER |
user_id |
INTEGER |
charged_at |
DATETIME |
amount |
FLOAT |
Output:
| Column | Type |
|---|---|
user_id |
INTEGER |
month |
VARCHAR |
total_expense |
FLOAT |
expense_diff |
FLOAT |
.
.
.
.
Comments