Advanced_SQL_Assignment_with_Answers
Advanced_SQL_Assignment_with_Answers
Scenario
You are hired as a data analyst for a company that manages customers, their orders, shipments,
and employee relationships. Your task is to use SQL to extract insights, optimize queries, and
analyze
1. Customers
|-------------|------------|------------|-----|---------|
|3 | David | Robinson | 22 | UK |
|4 | John | Reinhardt | 25 | UK |
2. Orders
|----------|------------|---------|-------------|
|1 | Keyboard | 400.00 | 4 |
|2 | Mouse | 300.00 | 4 |
|3 | Monitor | 12000.00 | 3 |
|4 | Keyboard | 400.00 | 1 |
|5 | Mousepad | 250.00 | 2 |
3. Shippings
|-------------|------------|----------|
|1 | Pending |2 |
|2 | Pending |4 |
|3 | Delivered | 3 |
|4 | Pending |5 |
|5 | Delivered | 1 |
a. Query: List all customers and their corresponding order details. Include customers who haven't
Answer:
FROM Customers c
ON c.customer_id = o.customer_id;
b. Query: Create a report showing all employees and their respective managers. Include employees
Answer:
FROM Employees e1
LEFT JOIN Employees e2
ON e1.manager_id = e2.employee_id;
2. Combining Queries
a. Query: Combine the results of customers who have either placed orders or have shipments,
Answer:
FROM Customers
WHERE customer_id IN (
UNION
);
3. Query Optimization
a. Query: Write an optimized query to find the total amount of orders placed by each customer.
Answer:
FROM Customers c
JOIN Orders o
ON c.customer_id = o.customer_id
a. Query: Create a hierarchy of employees, showing their name, position, and their manager's
name.
Answer:
WITH EmployeeHierarchy AS (
FROM Employees e1
ON e1.manager_id = e2.employee_id
Answer:
FROM Customers c
ON c.customer_id = o.customer_id
UNION
FROM Orders o
ON c.customer_id = o.customer_id;
6. Advanced Challenge
Answer:
SUM(o.amount) AS total_order_amount,
COALESCE(s.status, 'No Shipments') AS shipment_status,
CASE
END AS customer_type
FROM Customers c
ON c.customer_id = o.customer_id
ON c.customer_id = s.customer