For each user, rank their transactions by transaction_date ascending, with ties broken by transaction_id ascending, so the earliest transaction has rank 1. If a user has n transactions, return the one at rank FLOOR((n + 1) / 2). Report that rank as nth_transaction.
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, nth_transaction, in that order, one row per user. nth_transaction is the integer rank of the returned transaction within that user. 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 | 20.00 | 2024-03-01 09:00:00 |
| 2 | 1 | 35.00 | 2024-03-02 14:00:00 |
| 3 | 1 | 15.00 | 2024-03-05 11:00:00 |
| 4 | 2 | 50.00 | 2024-03-03 10:00:00 |
| 5 | 2 | 10.00 | 2024-03-01 08:00:00 |
| 6 | 2 | 70.00 | 2024-03-03 10:00:00 |
| 7 | 2 | 5.00 | 2024-03-04 16:00:00 |
| 8 | 3 | 99.99 | 2024-03-02 12:00:00 |
Expected output:
| user_id | transaction_id | amount | transaction_date | nth_transaction |
|---|
| 1 | 2 | 35.00 | 2024-03-02 14:00:00 | 2 |
| 2 | 4 | 50.00 | 2024-03-03 10:00:00 | 2 |
| 3 | 8 | 99.99 | 2024-03-02 12:00:00 | 1 |
User 1 has 3 transactions, so the target rank is (3 + 1) / 2 = 2, which is transaction 2. User 2 has 4 transactions in the order 5, 4, 6, 7 (transactions 4 and 6 share a timestamp and the lower id goes first), and the target rank is FLOOR(5 / 2) = 2, which is transaction 4. User 3 has one transaction, so rank 1 is returned.
Constraints and Clarifications
-
The table has at most
104
rows.
-
user_id
is a positive integer and
amount
is a positive decimal.
-
Each user has at least one transaction, and no column contains NULL.
-
Because
transaction_id
is the primary key, the order by
transaction_date
then
transaction_id
is strict, and exactly one row is returned per user.
-
For an even count the formula picks the lower middle transaction (rank 2 of 4). For a single transaction it picks rank 1.