cswork / libraryOpen practice workspace

Coding questions · Atlassian

Identify Top-3 Users by Recent Total Spend

This question evaluates SQL data manipulation competencies such as aggregation, joins, time-based filtering, and ranking to compute recent user spending; it falls under the Data Manipulation (SQL/Python) domain and targets practical application.

Users

+----+-------+-------------+
| id | name  | joined_date |
+----+-------+-------------+
| 1  | Alice | 2023-01-02  |
| 2  | Bob   | 2023-02-14  |
| 3  | Carol | 2023-02-20  |
+----+-------+-------------+

Orders

+-----+---------+------------+--------+
| id  | user_id | order_date | amount |
+-----+---------+------------+--------+
| 101 | 1       | 2023-03-01 | 120.0  |
| 102 | 2       | 2023-03-02 |  80.0  |
| 103 | 1       | 2023-03-05 | 240.0  |
+-----+---------+------------+--------+
Scenario

SQL technical screen assessing medium-difficulty query skills on e-commerce data.

Question

Write a SQL query that returns the top-3 users by total spend in the last 30 days, including user_id, user_name, and total_amount.

Hints

Use window functions or ORDER BY/LIMIT; remember date filtering.

Top-3 Users by Recent Spend (Including Zeros)

Write a SQL query that returns the top 3 users by total spend between 2025-05-03 and 2025-06-01 (inclusive). If fewer than three users have placed orders in that period, still return exactly three users by including users whose total spend is zero. Output columns: user_id, user_name, and total_amount. Order the result by total_amount in descending order; break ties by user_id in ascending order.

Table Users

columntypeconstraints
idINTEGERPRIMARY KEY
nameVARCHAR(100)
joined_dateDATE

Sample data:

idjoined_datename
12023-01-02Alice
22023-02-14Bob
32023-02-20Carol

Table Orders

columntypeconstraints
idINTEGERPRIMARY KEY
user_idINTEGERFOREIGN KEY REFERENCES Users(id)
order_dateDATE
amountDECIMAL(10,2)

Sample data:

amountidorder_dateuser_id
1201012025-05-101
801022025-05-202
2401032025-05-251

Expected output

Top 3 users by total spend between 2025-05-03 and 2025-06-01 (inclusive). Users with no orders in that window are included (with total_amount = 0) if needed to reach 3 rows. Sorted by total_amount descending, then user_id ascending.

total_amountuser_iduser_name
3601Alice
802Bob
03Carol

Hints

  1. Use a LEFT JOIN so users without orders in the date range are still returned.
  2. Filter orders to the range 2025-05-03 through 2025-06-01 in the join condition.
  3. Use COALESCE around SUM to treat missing order amounts as zero, then ORDER BY the sum and LIMIT 3.