Average Transaction Amount per User with at Least Two Transactions
Company: PayPal
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
For each user with at least two transactions, return `user_id` and the average `amount` of that user's transactions as `avg_transaction_amount`, rounded to 2 decimal places. Order the result by `user_id` ascending.
```hint Rounding the average
Round the finished average, and keep it as an exact decimal while you do, so that a value such as 10.005 rounds the way you expect.
```
### Input Table(s)
`transactions`
| Column | Type | Meaning |
|---|---|---|
| transaction_id | INT | Transaction identifier. Primary key. |
| user_id | INT | User who made the transaction. NOT NULL. |
| amount | DECIMAL(10,2) | Transaction amount. NOT NULL, always positive. |
| transaction_date | DATE | Date of the transaction. NOT NULL. |
Keys: `transaction_id` is the primary key. A user can have any number of rows.
### Output Contract
- Columns, in this order: `user_id`, `avg_transaction_amount`.
- One row per user who has 2 or more transactions. Users with a single transaction do not appear.
- `avg_transaction_amount` is the mean of the user's `amount` values, rounded to 2 decimal places with halves rounded away from zero (PostgreSQL `ROUND` on a `numeric`).
- Sort by `user_id` ascending. Each user appears once, so the order is fully determined.
### Example
`transactions`
| transaction_id | user_id | amount | transaction_date |
|---|---|---|---|
| 1 | 7 | 20.00 | 2024-03-01 |
| 2 | 3 | 10.00 | 2024-03-01 |
| 3 | 5 | 99.99 | 2024-03-02 |
| 4 | 7 | 35.50 | 2024-03-03 |
| 5 | 12 | 8.40 | 2024-03-03 |
| 6 | 3 | 10.01 | 2024-03-04 |
| 7 | 12 | 8.40 | 2024-03-05 |
| 8 | 7 | 40.00 | 2024-03-06 |
Expected output:
| user_id | avg_transaction_amount |
|---|---|
| 3 | 10.01 |
| 7 | 31.83 |
| 12 | 8.40 |
User 3 averages (10.00 + 10.01) / 2 = 10.005, which rounds to 10.01. User 7 averages 95.50 / 3 = 31.8333..., which rounds to 31.83. User 12 has two transactions of the same amount, and both count, so the average is 8.40. User 5 has only one transaction and is left out.
### Constraints and Clarifications
- The table has between 1 and 10,000 rows.
- `user_id` is between 1 and 10,000.
- `amount` is never NULL and always positive.
- Two transactions with the same amount are still two transactions. Count rows, not distinct amounts.
- `transaction_date` does not affect the result. Every transaction in the table counts.
- If no user has two transactions, the result is empty.
Overview: Write a SQL query that returns the average transaction amount, rounded to two decimals, for every user with at least two transactions, sorted by user. It tests GROUP BY, filtering groups with HAVING, counting rows correctly when amounts repeat, and rounding an aggregate.