cswork / libraryOpen practice workspace

Coding questions · Amazon

List Top Customers and Monthly Order Counts in SQL

This question evaluates a candidate's ability to perform SQL aggregation, grouping, top‑N selection, and date-based summarization to compute customer spend and chronological monthly order counts.

Orders

order_idcustomer_idorder_dateamount
11012023-01-05120.50
21022023-01-1075.00
31012023-01-1240.25
41032023-01-15220.90
51042023-01-2015.00
Scenario

Analyst must query customer orders stored in a relational database.

Question

Write SQL to list the top three customers by total spend. Write SQL to return monthly order counts for 2023, ordered chronologically.

Hints

Group-by, aggregates, date functions, ordering.

Top 3 customers by total spend

Using the Orders table, return the top three customers by total spend across all orders. For each customer, compute their total spend, then sort the results by total spend descending. Break ties by customer_id ascending.

Table Orders

columntypeconstraints
order_idINTEGERPRIMARY KEY, NOT NULL
customer_idINTEGERNOT NULL
order_dateDATENOT NULL
amountDECIMAL(10,2)NOT NULL

Sample data:

amountcustomer_idorder_dateorder_id
120.51012023-01-051
751022023-01-102
40.251012023-01-123
220.91032023-01-154
151042023-01-205

Expected output

Top three customers by total spend across all orders in the sample data, sorted by total spend descending and then customer_id ascending.

customer_idtotal_spend
103220.9
101160.75
10275

Hints

  1. Use SUM(amount) grouped by customer_id to calculate total spend per customer.
  2. Order by total_spend descending and customer_id ascending, then LIMIT 3.

Monthly order counts for 2023

Using the Orders table, return monthly order counts for the calendar year 2023. Output one row per month that has at least one order, labeled as YYYY-MM, ordered chronologically by month.

Table Orders

columntypeconstraints
order_idINTEGERPRIMARY KEY, NOT NULL
customer_idINTEGERNOT NULL
order_dateDATENOT NULL
amountDECIMAL(10,2)NOT NULL

Sample data:

amountcustomer_idorder_dateorder_id
120.51012023-01-051
751022023-01-102
40.251012023-01-123
220.91032023-01-154
151042023-01-205

Expected output

For the sample data, all orders occur in January 2023, so the result has a single row with the count of 5 for month 2023-01.

monthorder_count
2023-015

Hints

  1. Filter the date range to 2023 using order_date >= DATE '2023-01-01' and < DATE '2024-01-01'.
  2. Use DATE_TRUNC to group by month and TO_CHAR to format the month as YYYY-MM.