๐ฅ SQL Interview Case Studies (Advanced Business Scenarios) ๐ฏ
๐ง Case Study 1: Find Repeat Customers
๐ Orders Table
order_id customer_id
1 101
2 102
3 101
โ Business Question
Find customers who placed more than 1 order.
โ
Solution
SELECT customer_id,
COUNT(*) AS total_orders
FROM orders
GROUP BY customer_id
HAVING COUNT(*) > 1;
๐ง Case Study 2: Highest Paid Employee Per Department
โ Business Question
Find highest paid employee in every department.
โ
Solution
WITH RankedEmployees AS (
SELECT *,
ROW_NUMBER() OVER(
PARTITION BY department
ORDER BY salary DESC
) rn
FROM employees
)
SELECT *
FROM RankedEmployees
WHERE rn = 1;
๐ง Case Study 3: Find Inactive Customers
โ Business Question
Customers who haven't ordered in the last 6 months.
โ
Solution
SELECT c.customer_id,
c.name
FROM customers c
LEFT JOIN orders o
ON c.customer_id = o.customer_id
GROUP BY c.customer_id, c.name
HAVING MAX(o.order_date) <
DATE_SUB(CURDATE(), INTERVAL 6 MONTH);
๐ง Case Study 4: Product Generating Highest Revenue
๐ Sales Table
product_id amount
โ
Solution
SELECT product_id,
SUM(amount) AS revenue
FROM sales
GROUP BY product_id
ORDER BY revenue DESC
LIMIT 1;
๐ง Case Study 5: Employee Salary Above Department Average
โ
Solution
WITH DeptAvg AS (
SELECT department,
AVG(salary) avg_salary
FROM employees
GROUP BY department
)
SELECT e.*
FROM employees e
JOIN DeptAvg d
ON e.department = d.department
WHERE e.salary > d.avg_salary;
๐ง Case Study 6: Running Total Sales
โ Business Question
Calculate cumulative sales.
โ
Solution
SELECT order_date,
amount,
SUM(amount) OVER(
ORDER BY order_date
) AS running_total
FROM sales;
๐ง Case Study 7: Top 3 Products Per Category
โ
Solution
WITH RankedProducts AS (
SELECT *,
ROW_NUMBER() OVER(
PARTITION BY category
ORDER BY sales DESC
) rn
FROM products
)
SELECT *
FROM RankedProducts
WHERE rn <= 3;
๐ฏ Practice Tasks
1๏ธโฃ Find customer with highest number of orders
2๏ธโฃ Find lowest salary employee per department
3๏ธโฃ Find products never sold
4๏ธโฃ Find departments with average salary > company average
5๏ธโฃ Find month with lowest sales
โก Mini Challenge ๐ฅ
Banking Scenario
Tables:
Accounts
account_id customer_name
Transactions
transaction_id account_id amount transaction_date
Question
๐ Find the top 3 customers with highest total transaction amount in the last 1 year.
๐ฅ Interview Tip
When solving case studies:
1๏ธโฃ Understand business question
2๏ธโฃ Identify tables
3๏ธโฃ Identify JOINs
4๏ธโฃ Identify Aggregations
5๏ธโฃ Decide whether Window Function is needed
Double Tap โค๏ธ For More
Post #3246
68
- โค 1