Chuyển đến nội dung

Bài 62 · Projects

Final project: Shop Sales Review

Finish the Data Analyst path: query a sample shop with SQL, verify totals in Python and a spreadsheet, chart the results and present honest findings.

The owner of a small online shop, which we will call Lantern Row (an invented business), sends you one message: "How did 2025 go, and what should we look at before planning next year?" The data is the site's sample shop database: categories, products, customers, orders and order lines.

By the end you will have a set of checked queries, a reconciliation in Python and in a spreadsheet, two or three charts, an optional dashboard and a five-slide findings presentation. The site cannot grade the whole project. The checkpoints only compare the results of your code with the results of a reference solution.

What you need first

This is the last step of the Data Analyst path. It uses SQL, especially grouping and multiple joins; Excel, including pivot tables; School Statistics; Python; pandas; Data Visualization and Power BI.

You can run the checkpoints here. Build the spreadsheet, dashboard and presentation in real tools on your own computer. Any spreadsheet program works for the check, and slides can come from any presentation tool.

The brief

  1. Restate the owner's question as three smaller questions that data can answer.
  2. Define revenue in writing. In this project it means quantity * unit_price for order lines whose order is shipped or delivered. Shipping fees are excluded.
  3. Report revenue and order count by month, and revenue and share by category.
  4. Show how much order value is not counted as revenue, and why.
  5. Reconcile your totals in at least two independent ways.
  6. Make two or three honest charts.
  7. Present findings, limits and next steps in no more than five slides.

Milestones

1. Frame the question and inspect the data

Write your three questions, for example: "How did completed sales change by month?", "Which categories bring in the most revenue?" and "How much value is still pending or was cancelled?" Then count the rows in each table, list the order statuses and find the first and last order dates.

Why: a clear definition stops two people from getting two different "totals" from the same data.

Hint: an order has many order lines. After you join them, COUNT(*) counts lines, not orders.

Done when: you have a short note with your questions, your revenue definition and the period the data covers.

2. Answer the questions with SQL

Complete these three checkpoints on the shop database.

SQL Checkpoint 1: completed sales by month · database: shop

Your task: For orders with status shipped or delivered, return the columns month (text such as 2025-01), orders (number of different orders) and revenue (sum of quantity times unit_price, rounded to 2 decimals). Sort by month ascending.

Hint

Join orders to order_items, filter the status, and count distinct order ids.

Press Run (or Ctrl + Enter) to see the result here.

✅ Correct. Your result matches. ❌ Not yet. Check the output and try again. The answer could not be checked. Please try again.

Expected result


        

One possible solution

SELECT substr(o.ordered_at, 1, 7) AS month,
       COUNT(DISTINCT o.id) AS orders,
       ROUND(SUM(i.quantity * i.unit_price), 2) AS revenue
FROM orders AS o
JOIN order_items AS i ON i.order_id = o.id
WHERE o.status IN ('shipped', 'delivered')
GROUP BY month
ORDER BY month;
SQL Checkpoint 2: category share · database: shop

Your task: For shipped and delivered orders, return category (the category name), units (total quantity), revenue (rounded to 2 decimals) and share_pct (this category's percentage of all completed revenue, rounded to 1 decimal). Sort by revenue descending, then category ascending.

Hint

A common table expression of completed sales lines lets you reuse the same filter for the overall total.

Press Run (or Ctrl + Enter) to see the result here.

✅ Correct. Your result matches. ❌ Not yet. Check the output and try again. The answer could not be checked. Please try again.

Expected result


        

One possible solution

WITH sales AS (
    SELECT c.name AS category, i.quantity, i.quantity * i.unit_price AS amount
    FROM orders AS o
    JOIN order_items AS i ON i.order_id = o.id
    JOIN products AS p ON p.id = i.product_id
    JOIN categories AS c ON c.id = p.category_id
    WHERE o.status IN ('shipped', 'delivered')
)
SELECT category,
       SUM(quantity) AS units,
       ROUND(SUM(amount), 2) AS revenue,
       ROUND(100.0 * SUM(amount) / (SELECT SUM(amount) FROM sales), 1) AS share_pct
FROM sales
GROUP BY category
ORDER BY revenue DESC, category;
SQL Checkpoint 3: value by status · database: shop

Your task: Across all orders, return status, orders (number of different orders) and line_value (sum of quantity times unit_price, rounded to 2 decimals). Sort by line_value descending, then status ascending.

Hint

This is the same join as before, with no status filter.

Press Run (or Ctrl + Enter) to see the result here.

✅ Correct. Your result matches. ❌ Not yet. Check the output and try again. The answer could not be checked. Please try again.

Expected result


        

One possible solution

SELECT o.status,
       COUNT(DISTINCT o.id) AS orders,
       ROUND(SUM(i.quantity * i.unit_price), 2) AS line_value
FROM orders AS o
JOIN order_items AS i ON i.order_id = o.id
GROUP BY o.status
ORDER BY line_value DESC, o.status;

Why: the third query keeps your definition visible. A reader can see what you left out instead of discovering it later. Do not call pending value "lost": the data does not say what will happen to those orders.

Done when: all three checkpoints pass and the completed rows of checkpoint 3 add up to the total of checkpoint 1.

3. Verify and describe in Python

Copy your monthly results into Python and write a summary function. It recomputes the totals outside the database and turns rows into facts you can say aloud.

Python Checkpoint 4: summarize the months

Your task: Write summarize(rows). Each row is a tuple (month, orders, revenue), in any order. Return a dict with these keys: total (revenue sum, rounded to 2), average_order (total revenue divided by total orders, rounded to 2), median_month (median of the monthly revenue values, rounded to 2), best_month (month with the highest revenue; on a tie, the earliest month) and thin_months (sorted list of months with fewer than 5 orders). For an empty list, or when there are no orders, average_order is None. For an empty list, total is 0, median_month and best_month are None and thin_months is an empty list.

Hint

The average order value is a ratio of two totals, not the average of monthly averages.

Press Run (or Ctrl + Enter) to see the result here.

✅ Correct. Your result matches. ❌ Not yet. Check the output and try again. The answer could not be checked. Please try again.

Expected result


        

One possible solution

from statistics import median

def summarize(rows):
    total = sum(r[2] for r in rows)
    orders = sum(r[1] for r in rows)
    best = None
    if rows:
        best = sorted(rows, key=lambda r: (-r[2], r[0]))[0][0]
    return {
        "total": round(total, 2),
        "average_order": round(total / orders, 2) if orders else None,
        "median_month": round(median(r[2] for r in rows), 2) if rows else None,
        "best_month": best,
        "thin_months": sorted(r[0] for r in rows if r[1] < 5),
    }

Why: an average of monthly averages gives a quiet month the same weight as a busy one. The median month and the list of thin months warn you when a few orders drive a big swing.

Hint: for each unusual month, count the orders behind it and look at the largest one. If you prefer pandas, load the same joined rows into a DataFrame and compare groupby totals with your SQL.

Done when: the Python total matches your SQL total to the cent, and you have noted every thin month.

4. Check in a spreadsheet

On your computer, export the completed order lines as CSV with these columns: order id, order date, category, quantity and unit price. Your database tool can export a query result, or you can copy the result table. Add a line_total column, then build:

  • a SUM of line_total as a control total;
  • a pivot table of line_total by category;
  • a SUMIFS formula for one month of your choice.

Count the data rows too, and compare that count with a COUNT(*) query using the same filter.

Why: a different tool catches truncated copies, numbers stored as text and dates read in the wrong locale. It does not catch a wrong definition, because you apply the same definition both times.

Done when: a small "checks" sheet lists each total from SQL and from the spreadsheet, with a difference of zero after rounding to cents. See auditing formulas if one does not match.

5. Chart the results

Start with a line or bar chart by month and a sorted bar chart by category. The program below runs here, but its numbers are placeholders. Replace them with your own results.

Python Chart template with placeholder numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Why: order counts on the bars stop readers from treating a tiny month as a major trend. Bar axes start at zero. Titles should say what is measured, and your final titles can state the finding. See choosing a chart and color and accessibility.

If you have access to Power BI Desktop, build a one-page report with a revenue card, both charts and a status filter, following your first report. Name measures clearly so that the status filter cannot silently change what "revenue" means. If you cannot run it, a spreadsheet dashboard is a reasonable substitute.

Done when: each chart answers one of your questions and its numbers match your checks sheet.

6. Present the findings

Use up to five slides: the question and definition; the year by month; the categories; what is excluded and what you cannot know; and recommended next checks. Write each finding as what you saw, how sure you are, and what to do next.

Be careful with causes. The database has no advertising, visitor, cost or profit data. It cannot show why a month was weak or which category earns the most profit. It can suggest what to investigate. One year also cannot establish a seasonal pattern.

Done when: you have rehearsed it aloud in under five minutes and every number traces back to a query.

Check your work

Criterion What good looks like
Question and definition Three answerable questions; revenue, status filter and shipping rule are written down
Queries Checkpoints pass; each query has a short comment saying what one result row means
Reconciliation SQL, Python and spreadsheet totals agree, with row counts recorded
Statistics Counts appear beside averages and shares; thin months are flagged
Charts Zero-based bars, clear titles and units, readable without relying on color
Findings Observations are separate from guesses; limits are stated
Reproducibility Another person could rebuild your numbers from your saved files

Common mistakes

Do not count orders with COUNT(*) after joining order lines. Do not add the shipping column after that join either, because each order's fee would repeat once per line. Do not use the current product price in place of the unit_price saved on the order line: prices can change after a sale. And do not write "category X is the most profitable" when you only measured revenue.

Take it further

  • Compare countries, and show the number of customers and orders next to each total.
  • Find which products appear in completed orders most often, then compare that ranking with the revenue ranking.
  • Compute the median order value from order-level totals and compare it with the mean.
  • List the extra data you would ask the owner for, and the question each item would answer.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. After joining orders to order lines, which expression counts orders?

    The join repeats an order once for each line, so you count distinct order ids.
  2. 2. One month has far fewer completed orders than the others. What is the best first response?

    A small count is a reason to look closer. It does not explain itself.
  3. 3. Your spreadsheet total matches SQL exactly. What does that show?

    Reconciliation catches calculation and transfer errors. It cannot validate the definition or measure profit.
  4. 4. How should you calculate average order value for the year?

    The ratio of the totals gives every order the same weight.
  5. 5. Which claim can this database support?

    It records sales. It has no advertising data, and one year cannot establish a yearly pattern.

Summary

  • Turn a broad request into answerable questions and a written definition.
  • Show what your definition excludes.
  • Reconcile totals across tools, while remembering that agreement does not prove the definition.
  • Put counts beside results that rest on small numbers.
  • Present observations, limits and next checks, and do not invent causes.

Back to the path: Data Analyst learning path

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.