Reading history

SQL Project: Sales Analysis Report for an Online Shop

7 min read Updated 0 views

Build a sales analysis report in SQL: related tables, a reporting view, average order value, monthly growth, category share, best sellers and customer segments.

This project puts the SQL course to work on a realistic task: a monthly sales report for a small online bookshop. You will design four related tables, create a view that joins them, and answer the questions a shop owner actually asks. How much did we sell? Are we growing? Which categories and books matter most? Who are our best customers?

In this project you will

  • Create related tables with primary and foreign keys
  • Build a reusable view over a four-table join
  • Calculate headline numbers such as average order value
  • Measure month-over-month growth with LAG
  • Find category shares, best sellers per category and customer segments

This project uses joins, views, GROUP BY, window functions and CASE. You can run the whole script in the SQLite shell or DB Browser for SQLite.

The Complete Script

-- 1. Schema and data: a small online bookshop
CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT, city TEXT, joined TEXT);
CREATE TABLE products  (id INTEGER PRIMARY KEY, title TEXT, category TEXT, price INTEGER);
CREATE TABLE shop_orders (id INTEGER PRIMARY KEY, customer_id INTEGER REFERENCES customers(id), ordered TEXT);
CREATE TABLE order_items (order_id INTEGER REFERENCES shop_orders(id),
                          product_id INTEGER REFERENCES products(id), qty INTEGER);
INSERT INTO customers VALUES
 (1,'Ayesha','Dhaka','2026-01-03'),(2,'Bashir','Sylhet','2026-01-10'),(3,'Chandni','Dhaka','2026-01-21'),
 (4,'Dipu','Khulna','2026-02-02'),(5,'Era','Chattogram','2026-02-15'),(6,'Fahim','Dhaka','2026-03-01');
INSERT INTO products VALUES
 (1,'Learn SQL','Programming',450),(2,'Python Basics','Programming',500),
 (3,'Bangla Poems','Literature',300),(4,'World History','History',650),(5,'Data Science 101','Programming',800);
INSERT INTO shop_orders VALUES
 (1,1,'2026-01-05'),(2,2,'2026-01-12'),(3,1,'2026-01-28'),(4,3,'2026-02-03'),(5,4,'2026-02-09'),
 (6,1,'2026-02-20'),(7,5,'2026-02-25'),(8,3,'2026-03-04'),(9,6,'2026-03-11'),(10,2,'2026-03-19'),
 (11,1,'2026-03-27'),(12,5,'2026-03-30');
INSERT INTO order_items VALUES
 (1,1,1),(1,3,2),(2,2,1),(3,5,1),(4,4,1),(4,3,1),(5,1,2),(6,2,1),(6,1,1),(7,3,3),
 (8,5,1),(8,2,1),(9,4,2),(10,1,1),(11,5,1),(11,3,1),(12,2,2);

-- 2. One reusable view with the value of every order line
CREATE VIEW sales AS
SELECT o.id AS order_id, o.ordered, strftime('%Y-%m', o.ordered) AS month,
       c.id AS customer_id, c.name AS customer, c.city,
       p.title, p.category, i.qty, i.qty * p.price AS revenue
FROM shop_orders o
JOIN customers c ON c.id = o.customer_id
JOIN order_items i ON i.order_id = o.id
JOIN products p ON p.id = i.product_id;

-- 3. Headline numbers
SELECT COUNT(DISTINCT order_id) AS orders,
       SUM(revenue) AS revenue,
       ROUND(1.0 * SUM(revenue) / COUNT(DISTINCT order_id), 1) AS avg_order_value
FROM sales;

-- 4. Revenue by month and growth on the previous month
SELECT month, SUM(revenue) AS revenue,
       ROUND(100.0 * (SUM(revenue) - LAG(SUM(revenue)) OVER (ORDER BY month))
             / LAG(SUM(revenue)) OVER (ORDER BY month), 1) AS growth_pct
FROM sales GROUP BY month ORDER BY month;

-- 5. Share of revenue by category
SELECT category, SUM(revenue) AS revenue,
       ROUND(100.0 * SUM(revenue) / SUM(SUM(revenue)) OVER (), 1) AS share_pct
FROM sales GROUP BY category ORDER BY revenue DESC;

-- 6. Best-selling book in each category
WITH ranked AS (
  SELECT category, title, SUM(qty) AS copies,
         RANK() OVER (PARTITION BY category ORDER BY SUM(qty) DESC) AS rk
  FROM sales GROUP BY category, title
)
SELECT category, title, copies FROM ranked WHERE rk = 1;

-- 7. Customer segments: how often and how much
SELECT customer, COUNT(DISTINCT order_id) AS orders, SUM(revenue) AS spent,
       CASE WHEN COUNT(DISTINCT order_id) >= 3 THEN 'loyal'
            WHEN COUNT(DISTINCT order_id) = 2 THEN 'returning'
            ELSE 'one-time' END AS segment
FROM sales GROUP BY customer_id ORDER BY spent DESC;

Output

+--------+---------+-----------------+
| orders | revenue | avg_order_value |
+--------+---------+-----------------+
| 12     | 11200   | 933.3           |
+--------+---------+-----------------+
(1 row)

+---------+---------+------------+
| month   | revenue | growth_pct |
+---------+---------+------------+
| 2026-01 | 2350    | NULL       |
| 2026-02 | 3700    | 57.4       |
| 2026-03 | 5150    | 39.2       |
+---------+---------+------------+
(3 rows)

+-------------+---------+-----------+
| category    | revenue | share_pct |
+-------------+---------+-----------+
| Programming | 7150    | 63.8      |
| Literature  | 2100    | 18.8      |
| History     | 1950    | 17.4      |
+-------------+---------+-----------+
(3 rows)

+-------------+---------------+--------+
| category    | title         | copies |
+-------------+---------------+--------+
| History     | World History | 3      |
| Literature  | Bangla Poems  | 7      |
| Programming | Python Basics | 5      |
| Programming | Learn SQL     | 5      |
+-------------+---------------+--------+
(4 rows)

+----------+--------+-------+-----------+
| customer | orders | spent | segment   |
+----------+--------+-------+-----------+
| Ayesha   | 4      | 3900  | loyal     |
| Chandni  | 2      | 2250  | returning |
| Era      | 2      | 1900  | returning |
| Fahim    | 1      | 1300  | one-time  |
| Bashir   | 2      | 950   | returning |
| Dipu     | 1      | 900   | one-time  |
+----------+--------+-------+-----------+
(6 rows)

Step by Step

1. The tables

Each fact lives in one place. A customer’s city is stored once in customers; a book’s price once in products. An order can contain several books, so the books of each order go in a separate order_items table with a quantity. This is the standard one-to-many design for orders.

2. The view

Almost every question needs the same four-table join, so it is written once as the sales view, one row per order line, with the line’s revenue (qty × price) and the month already worked out. Every later query reads from sales like a normal table, which keeps them short and consistent.

3. Headline numbers

12 orders brought in 11,200 taka, an average order value of 933.3 taka. COUNT(DISTINCT order_id) is essential: the view has one row per line, so a plain COUNT(*) would count 17 lines, not 12 orders. Multiplying by 1.0 forces decimal division.

4. Growth

LAG(SUM(revenue)) OVER (ORDER BY month) brings the previous month’s revenue onto each row. Revenue grew 57.4% from January to February and 39.2% from February to March. January has no previous month, so its growth is NULL.

5. Category share

SUM(SUM(revenue)) OVER () looks odd but is useful: the inner SUM totals each category, and the outer window SUM adds those totals across all rows to get the grand total. Programming books bring in almost two thirds (63.8%) of revenue.

6. Best sellers per category

RANK() numbers the books inside each category by copies sold, and the outer query keeps rank 1. In Programming, Python Basics and Learn SQL tie with 5 copies each, and RANK shows both. ROW_NUMBER would pick one of them arbitrarily.

7. Customer segments

A CASE expression labels customers by how often they order. Ayesha, with 4 orders and 3,900 taka, is the shop’s only loyal customer so far. Fahim and Dipu bought once; a “come back” offer for them would be a sensible next step.

Taking It Further

  • Add a status column to shop_orders and exclude cancelled orders from the view.
  • Find each customer’s first order month and count how many come back in later months (a simple cohort analysis).
  • Use the calendar technique to show months with no sales.
  • Report the median order value alongside the average.

Common Mistakes in Reports

  1. Counting lines instead of orders after joining to an items table.
  2. Integer division in percentages and averages: 2 / 3 is 0 in SQLite. Multiply by 1.0 or 100.0 first.
  3. Storing calculated totals in the orders table, where they can drift out of step with the items. Calculate them in a view.
  4. Ignoring ties when picking a “best” item.

Practice Exercises

Exercise 1. Show revenue by city, highest first.

Show answer
SELECT city, SUM(revenue) AS revenue
FROM sales GROUP BY city ORDER BY revenue DESC;

Dhaka leads with 7,450 taka from three customers.

Exercise 2. Which books have never been ordered?

Show answer
SELECT p.title
FROM products p
LEFT JOIN order_items i ON i.product_id = p.id
WHERE i.product_id IS NULL;

Every book in this data has been ordered at least once, so the result is empty. Add a new product and run it again to see it appear.

Frequently Asked Questions

Why use a view instead of a new table?

A view stores only the query, so it always reflects the current data. A table copy would need to be rebuilt every time an order is added.

Can I connect this report to Excel or Power BI?

Yes. Both connect directly to MySQL and PostgreSQL, and to SQLite through an ODBC driver. They can read the sales view like a table, so the charts refresh when the data changes.

Summary

  • Keep facts in related tables and build a view for reporting.
  • Count distinct orders, not joined lines.
  • Use LAG for growth and window sums for shares.
  • Rank with RANK to keep ties visible, and segment with CASE.

Next: SQL EXISTS and NOT EXISTS: Semi-Joins and Anti-Joins.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *