cswork / libraryOpen practice workspace

Coding questions · Visa

Compute Total Spent in 2023 Excluding Refunds

This question evaluates data manipulation and aggregation skills in Python (pandas) and SQL by testing transactional filtering, handling of refunds, and computation of per-user total spending.

transactions

+----------------+---------+-------------+--------+------------------+
| transaction_id | user_id | merchant_id | amount | transaction_date |
+----------------+---------+-------------+--------+------------------+
| 1              | 101     | 2001        | 120    | 2023-01-10       |
| 2              | 102     | 2002        | -20    | 2023-02-14       |
| 3              | 101     | 2001        | 30     | 2022-12-31       |
| 4              | 103     | 2003        | 55     | 2023-03-05       |
| 5              | 101     | 2002        | 75     | 2023-04-17       |
+----------------+---------+-------------+--------+------------------+
Scenario

Visa analytics role – technical round requiring the same data-manipulation task solved first in Python and then in SQL.

Question

Using Python (pandas), compute each user’s total amount spent in 2023, excluding refunds (negative amounts). Return user_id and total_spent sorted by total_spent descending. Rewrite the same solution in SQL, using a CTE and GROUP BY.

Hints

Filter dates, ignore negative amounts, aggregate, sort.

Total amount spent per user in 2023 excluding refunds

Using SQL with a CTE and GROUP BY, compute each user's total amount spent in calendar year 2023, excluding refunds (negative amounts). Return user_id and total_spent sorted by total_spent in descending order. Only include users who have at least one positive-amount transaction in 2023.

Table transactions

columntypeconstraints
transaction_idINTEGERPRIMARY KEY, NOT NULL
user_idINTEGERNOT NULL
merchant_idINTEGERNOT NULL
amountDECIMAL(10,2)NOT NULL
transaction_dateDATENOT NULL

Sample data:

amountmerchant_idtransaction_datetransaction_iduser_id
12020012023-01-101101
-2020022023-02-142102
3020012022-12-313101
5520032023-03-054103
7520022023-04-175101

Expected output

For each user with at least one positive-amount transaction in calendar year 2023, sum the amounts and order by the sum descending. Users with only refunds (negative amounts) in 2023 are excluded.

total_spentuser_id
195101
55103

Hints

  1. Filter to 2023 using a date range
  2. Exclude negative amounts (refunds)
  3. Aggregate with SUM grouped by user_id
  4. Order by total_spent descending
  5. Use a CTE to prefilter then aggregate