HardSQL challenge #193CTEMulti-JOINCOALESCELEFT JOINAggregation

Build a Product Performance Report with Two CTEs

For the top 20 active products by revenue, show units sold, revenue, average review, review count and margin.

The challenge runs on the SQLabHub practice database (SQLite) and uses the products, order_items and reviews tables. You can solve it in the browser, with nothing to install.

Solve This SQL Challenge

Why this question comes up

The product team's monthly review needs one row per active product with sales, reviews and margin together. Combining two child tables (order lines and reviews) in one report is exactly where totals usually go wrong, which is the point of this challenge.

The task

For each active product: units sold, revenue, average review rating, review count and profit margin %. Aggregate sales and reviews separately before joining them to products.

A correct answer returns 20 rows with 8 columns: name, category, price, units_sold, revenue, avg_review, review_count, margin_pct.

Tables used in this challenge

products 120 rows

id INTEGER (PK) · name TEXT · category TEXT · price REAL · cost REAL · stock INTEGER · sku TEXT · status TEXT · rating REAL · review_count INTEGER

First 3 rows of the products table
idnamecategorypricecoststockskustatusratingreview_count
1LEGO Creator Set 742pcsToys59.9919.8257SKU-000001activeNULL0
2Ergonomic Desk Mat XLOffice Supplies34.9910.85131SKU-000002active4.52
3Magnetic Phone Mount ProAutomotive24.999176SKU-000003active51

order_items 494 rows

id INTEGER (PK) · order_id INTEGER · product_id INTEGER · quantity INTEGER · unit_price REAL · subtotal REAL

First 3 rows of the order_items table
idorder_idproduct_idquantityunit_pricesubtotal
1176549.99249.95
2182332.9998.97
3165179.9979.99

reviews 192 rows

id INTEGER (PK) · product_id INTEGER · user_id INTEGER · rating INTEGER · comment TEXT · reviewed_at TEXT · helpful_votes INTEGER

First 3 rows of the reviews table
idproduct_iduser_idratingcommentreviewed_athelpful_votes
1321365Great product, exactly as described. Fast shipping!2023-03-1541
2301401Slightly disappointed, expected more for the price.2023-06-234
3311405Excellent build quality. Will buy again!2023-07-076

The first rows of each table are shown. See how all the tables relate on the database schema page.

Expected output

Expected output of the challenge
namecategorypriceunits_soldrevenueavg_reviewreview_countmargin_pct
4K Monitor 27"Electronics3491966314.5246
Laptop Pro 15"Electronics1299564955169
GPS Running WatchSports & Outdoors2292864123345
Adjustable Dumbbells 52.5lbSports & Outdoors2991750832468
Play Kitchen DeluxeToys1293747733267

First 5 of 20 rows. This is the output of the model solution on the practice database.

What you practise

  • Filtering rows with a WHERE condition
  • Summarising many rows into one value with COUNT, SUM, AVG, MIN or MAX
  • Grouping rows with GROUP BY to get one result row per group
  • Keeping every row of the left table with LEFT JOIN, matched or not
  • Naming an intermediate result with a WITH clause and reading from it
  • Replacing NULL with a default using COALESCE
  • Sorting the result with ORDER BY
  • Returning only the first rows with LIMIT

Hint and approach

Try the challenge first. Open these only when you need them.

Show the hint

Summarise order_items and reviews in two CTEs, then LEFT JOIN both to products. Joining the raw tables together would multiply the sales by the number of reviews.

Show the step-by-step approach

How the model solution is built, in the order the database evaluates it:

  1. Define a common table expression named sales:
    1. Read from the order_items table.
    2. Group the rows by product_id, so the result has one row for each value.
    3. For each group, compute SUM(quantity) and SUM(subtotal).
  2. Define a common table expression named ratings:
    1. Read from the reviews table.
    2. Group the rows by product_id, so the result has one row for each value.
    3. For each group, compute AVG(rating) and COUNT(*).
  3. Read from the products table.
  4. LEFT JOIN sales on sales.product_id = products.id. Rows from the left side that have no match are kept, with NULL in the joined columns.
  5. LEFT JOIN ratings on ratings.product_id = products.id. Rows from the left side that have no match are kept, with NULL in the joined columns.
  6. Filter in WHERE: keep the rows where products.status equals 'active'.
  7. ROUND() trims the calculated figures to a fixed number of decimals.
  8. COALESCE(x, 0) replaces a NULL result with 0.
  9. Sort the result by revenue descending.
  10. Keep only the first 20 rows with LIMIT.
Show the model solution
WITH sales AS (
  SELECT product_id, SUM(quantity) AS units_sold, SUM(subtotal) AS revenue
  FROM order_items
  GROUP BY product_id
),
ratings AS (
  SELECT product_id, AVG(rating) AS avg_review, COUNT(*) AS review_count
  FROM reviews
  GROUP BY product_id
)
SELECT p.name, p.category, p.price,
  COALESCE(s.units_sold, 0) AS units_sold,
  ROUND(COALESCE(s.revenue, 0), 2) AS revenue,
  ROUND(r.avg_review, 1) AS avg_review,
  COALESCE(r.review_count, 0) AS review_count,
  ROUND(100.0 * (p.price - p.cost) / p.price, 1) AS margin_pct
FROM products p
LEFT JOIN sales s ON s.product_id = p.id
LEFT JOIN ratings r ON r.product_id = p.id
WHERE p.status = 'active'
ORDER BY revenue DESC
LIMIT 20;

This query produced the expected output above. Yours does not have to match it word for word: any query that returns the same rows is correct.

What to watch for

One CTE summarises sales and another summarises reviews, each to one row per product, and only then are they joined to products. Joining order_items and reviews directly would repeat every order line once per review and overstate units and revenue. The margin uses 100.0 so the division is not truncated.

  • CTE (WITH). A CTE exists only for the single statement it is attached to. It is not a temporary table and cannot be reused by the next query.
  • LEFT JOIN. A WHERE condition on the right-hand table removes the unmatched rows and turns the LEFT JOIN back into an inner join. Conditions on that table go in the ON clause.
  • GROUP BY. Every selected column must either be in GROUP BY or sit inside an aggregate. SQLite accepts other columns and returns an arbitrary value for them; most databases raise an error.
Solve This SQL Challenge

Keep learning