Analyzing E-commerce data using SQL

1.8 Sample analytics | E commerce

Here are some sample problem statements that a data analyst may have to solve in the e-commerce or any sales data base based company.

1. Write a query to find the names and ages of all customers who have placed an order in the past month.

Customers table:

Customer IDNameAge
1Alice25
2Bob32
3Carol21
4Dave28

Orders table:

Order IDCustomer IDOrder Date
112021-12-01
222021-12-03
332021-11-30
412021-12-15
542021-12-20

Solution:

SELECT c.name, c.age
FROM customers c
JOIN orders o
ON c.customer_id = o.customer_id
WHERE o.order_date BETWEEN DATEADD(month, -1, GETDATE()) AND GETDATE();

This query returns:

NameAge
Alice25
Bob32
Dave28

2. Write a query to find the top 3 best-selling products by total quantity sold.

Products table:

Product IDNamePrice
1T-shirt20
2Jeans50
3Jacket80
4Sneakers40

Order_items table:

Order IDProduct IDQuantity
112
121
222
231
333
413
422
531
542

Solution:

SELECT p.name, SUM(oi.quantity) as Total Quantity
FROM products p
JOIN order_items oi
ON p.product_id = oi.product_id
GROUP BY p.name
ORDER BY Total Quantity DESC
LIMIT 3;

This query returns:

NameTotal Quantity
Jacket4
T-shirt5
Jeans3

3. Write a query to find the average order value for each customer.

Customers table:

Customer IDNameAge
1Alice25
2Bob32
3Carol21
4Dave28

Orders table:

Order IDCustomer IDTotal Price
11100
22150
3350
41200
5475

Solution:

SELECT c.name, AVG(o.total_price) as Average Order Value
FROM customers c
JOIN orders o
ON c.customer_id = o.customer_id
GROUP BY c.name;

This query returns:

NameAverage Order Value
Alice150
Bob150
Carol50
Dave75

4. Write a query to find the most popular product among customers who are under the age of 25.

Products table:

Product IDNamePrice
1T-shirt20
2Jeans50
3Jacket80
4Sneakers40

Order items table:

Order IDProduct IDQuantity
112
121
222
231
333
413
422
531
542

Customers table:

Customer IDNameAge
1Alice25
2Bob32
3Carol21
4Dave28

Solution:

SELECT p.name, COUNT(o.order_id) as Order Count
FROM products p
JOIN order_items oi
ON p.product_id = oi.product_id
JOIN orders o
ON oi.order_id = o.order_id
JOIN customers c
ON o.customer_id = c.customer_id
WHERE c.age < 25
GROUP BY p.name
ORDER BY Order Count DESC
LIMIT 1;

This query returns:

NameOrder Count
Jacket2

Leave a Comment