For each user in the transactions table, return the transaction or transactions with the most recent transaction_date. If several of a user's transactions share the latest transaction_date, return all of them.
Input Table(s)
transactions
| Column | Type | Meaning |
|---|
| transaction_id | INT | Unique id of the transaction |
| user_id | INT | User who made the transaction |
| amount | DECIMAL(10,2) | Transaction amount |
| transaction_date | TIMESTAMP | Date and time of the transaction |
Primary key: transaction_id. All four columns are NOT NULL.
Output Contract
Return the columns user_id, transaction_id, amount, transaction_date, in that order, one row per returned transaction. Sort by user_id ascending, then transaction_id ascending. Return amount and transaction_date as stored, with no rounding or reformatting.
Example
Input transactions:
| transaction_id | user_id | amount | transaction_date |
|---|
| 1 | 1 | 25.00 | 2024-01-05 10:00:00 |
| 2 | 1 | 40.50 | 2024-01-07 09:30:00 |
| 3 | 2 | 15.00 | 2024-01-03 12:00:00 |
| 4 | 2 | 60.00 | 2024-01-03 12:00:00 |
| 5 | 2 | 8.25 | 2024-01-02 18:45:00 |
| 6 | 3 | 100.00 | 2024-01-01 08:00:00 |
| 7 | 1 | 12.00 | 2024-01-07 08:15:00 |
Expected output:
| user_id | transaction_id | amount | transaction_date |
|---|
| 1 | 2 | 40.50 | 2024-01-07 09:30:00 |
| 2 | 3 | 15.00 | 2024-01-03 12:00:00 |
| 2 | 4 | 60.00 | 2024-01-03 12:00:00 |
| 3 | 6 | 100.00 | 2024-01-01 08:00:00 |
User 1 has two transactions on 2024-01-07, and only transaction 2 has the latest time (09:30). User 2 has two transactions at exactly 2024-01-03 12:00:00, so both are returned. User 3 has one transaction.
Constraints and Clarifications
-
The table has at most
104
rows.
-
user_id
is a positive integer and
amount
is a positive decimal.
-
No column contains NULL.
-
"Latest" compares the full
transaction_date
value, date and time. Two transactions on the same calendar day at different times are not tied.
-
Every user who appears in the table appears in the output with at least one row.