Q28. Salary bands
Classify salaries as High (100000 or more), Medium (70000 to 99999) or Low (below 70000) and count employees in each band.
SELECT CASE WHEN salary >= 100000 THEN 'High'
WHEN salary >= 70000 THEN 'Medium'
ELSE 'Low'
END AS salary_band,
COUNT(*) AS emp_count
FROM employees
GROUP BY CASE WHEN salary >= 100000 THEN 'High'
WHEN salary >= 70000 THEN 'Medium'
ELSE 'Low'
END
ORDER BY MIN(salary) DESC;
-- salary_band | emp_count
-- High | 4
-- Medium | 9
-- Low | 7Q29. Delivered vs cancelled orders per customer (conditional aggregation)
For customers who have at least one cancelled order, show how many orders were delivered and how many were cancelled.
SELECT c.name,
SUM(CASE WHEN o.status = 'Delivered' THEN 1 ELSE 0 END) AS delivered,
SUM(CASE WHEN o.status = 'Cancelled' THEN 1 ELSE 0 END) AS cancelled
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.name
HAVING SUM(CASE WHEN o.status = 'Cancelled' THEN 1 ELSE 0 END) > 0
ORDER BY c.name;
-- name | delivered | cancelled
-- Divya | 1 | 1
-- Heena | 0 | 1Q30. Customers spending above the average customer (CTE)
Using a CTE, find customers whose total delivered spend is above the average total spend per customer.
WITH spend AS (
SELECT c.customer_id, c.name,
SUM(oi.quantity * p.price) AS total_spend
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id
WHERE o.status = 'Delivered'
GROUP BY c.customer_id, c.name
)
SELECT name, total_spend
FROM spend
WHERE total_spend > (SELECT AVG(total_spend) FROM spend)
ORDER BY total_spend DESC;
-- name | total_spend
-- Aman | 140500
-- Bina | 125250
-- Gopal | 60000Q31. All business cities (UNION)
List every distinct city that appears either as a department location or as a customer city.
SELECT location AS city FROM departments
UNION
SELECT city FROM customers
ORDER BY city;
-- Bangalore, Chennai, Delhi, Mumbai, PuneQ32. Common and exclusive cities (INTERSECT / EXCEPT)
Find (a) cities that have both a department and a customer, and (b) customer cities where we have no department.
-- (a) cities with both
SELECT city FROM customers
INTERSECT
SELECT location FROM departments
ORDER BY city;
-- Bangalore, Delhi, Mumbai
-- (b) customer cities with no department
SELECT city FROM customers
EXCEPT
SELECT location FROM departments
ORDER BY city;
-- Chennai, Pune
-- MySQL: use EXISTS / NOT EXISTS (INTERSECT/EXCEPT need MySQL 8.0.31+)