cswork / libraryOpen practice workspace

Coding questions · Amazon

Calculate Monthly Revenue from Orders in 2023

This question evaluates proficiency in SQL-based data manipulation, including aggregation, date extraction, and combining transactional tables to produce business metrics, and falls under the Data Manipulation (SQL/Python) domain.

orders

idorder_datecustomer
12023-01-03101
22023-02-14102
32023-02-20101

order_items

idorder_iditemprice
11A25.00
21B15.00
32C35.00
Scenario

Online assessment: SQL section with order and order_item data.

Question

Given tables orders and order_items, write a SQL query that returns each calendar month of 2023 and the corresponding total revenue (sum of price).

Hints

JOIN the two tables, filter by year, GROUP BY month extracted from order_date, ORDER BY month.

Monthly Revenue for 2023

You are given two tables, orders and order_items. Write a SQL query that returns each calendar month of 2023 (months 1 through 12) and the corresponding total revenue for that month, where revenue is defined as the sum of price from order_items joined to orders. The result should include months with zero revenue and be ordered by month ascending.

Table orders

columntypeconstraints
idINTEGERPRIMARY KEY, NOT NULL
order_dateDATENOT NULL
customerINTEGERNOT NULL

Sample data:

customeridorder_date
10112023-01-03
10222023-02-14
10132023-02-20

Table order_items

columntypeconstraints
idINTEGERPRIMARY KEY, NOT NULL
order_idINTEGERNOT NULL, FOREIGN KEY REFERENCES orders(id)
itemVARCHAR(50)NOT NULL
priceDECIMAL(10,2)NOT NULL

Sample data:

iditemorder_idprice
1A125
2B115
3C235

Expected output

One row per calendar month of 2023 with the total revenue computed from order_items joined to orders. Includes months with zero revenue. Ordered by month ascending.

monthtotal_revenue
140
235
30
40
50
60
70
80
90
100
110
120

Hints

  1. JOIN orders to order_items on orders.id = order_items.order_id.
  2. Filter rows to year 2023 using the order_date column.
  3. GROUP BY the month extracted from order_date.
  4. ORDER BY the month number ascending.
  5. To include months with no orders, generate months 1–12 (e.g., using a recursive CTE or a numbers table) and LEFT JOIN the aggregated revenue.