You are given a table Transactions with the following columns:
user_id(int): The user identifierspend(decimal): The amount spent in the transactiontransaction_date(datetime): The date and time of the transaction
The combination of (user_id, transaction_date) is unique for each row.
Write a SQL query to find the third transaction for each user who has at least three transactions, where:
- The spending on the first transaction is lower than the spending on the third transaction
- The spending on the second transaction is lower than the spending on the third transaction
Return the result ordered by user_id in ascending order.
Table Schema
| Column Name | Type | Description |
|---|---|---|
user_id
PK
|
int | User identifier |
spend
|
decimal | Amount spent in the transaction |
transaction_date
PK
|
datetime | Date and time of the transaction |
Input & Output
| user_id | spend | transaction_date |
|---|---|---|
| 1 | 100 | 2024-01-01 |
| 1 | 120 | 2024-01-02 |
| 1 | 200 | 2024-01-03 |
| 2 | 50 | 2024-01-01 |
| 2 | 80 | 2024-01-02 |
| 2 | 70 | 2024-01-03 |
| user_id | spend | transaction_date |
|---|---|---|
| 1 | 200 | 2024-01-03 |
User 1's third transaction (200.00) is greater than both first (100.00) and second (120.00) transactions, so it's included. User 2's third transaction (70.00) is not greater than the second transaction (80.00), so it's excluded.
| user_id | spend | transaction_date |
|---|---|---|
| 3 | 150 | 2024-01-01 |
| 3 | 200 | 2024-01-02 |
| 4 | 75 | 2024-01-01 |
| 4 | 85 | 2024-01-02 |
| 4 | 95 | 2024-01-03 |
| user_id | spend | transaction_date |
|---|---|---|
| 4 | 95 | 2024-01-03 |
User 3 has only 2 transactions, so no result for them. User 4's third transaction (95.00) is greater than both first (75.00) and second (85.00) transactions, so it's included.
Constraints
-
1 ≤ user_id ≤ 1000 -
0.01 ≤ spend ≤ 10000.00 -
transaction_dateis a valid datetime - Each user has at least 1 transaction