SQL Questions Answers
SQL Questions Answers
Q3: Find students who scored above the course average grade.
A3:
SELECT s.name, c.title, e.grade
FROM enrollments e
JOIN students s ON s.student_id = e.student_id
JOIN courses c ON c.course_id = e.course_id
WHERE e.grade > (
SELECT AVG(e2.grade)
FROM enrollments e2
WHERE e2.course_id = e.course_id
);
Q3: Retrieve employees who earn more than their department’s average salary.
A3:
SELECT e.*
FROM employees e
JOIN (
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
) dept_avg ON e.department_id = dept_avg.department_id
WHERE e.salary > dept_avg.avg_salary;
Q2: Find the top 3 best-selling products based on total quantity sold.
A2:
SELECT p.product_name, SUM(oi.quantity) AS total_sold
FROM products p
JOIN order_items oi ON p.product_id = oi.product_id
GROUP BY p.product_name
ORDER BY total_sold DESC
LIMIT 3;
Q3: Get customers who haven’t placed any orders in the last 6 months.
A3:
SELECT c.*
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id AND o.order_date > CURRENT_DATE
- INTERVAL '6 months'
GROUP BY c.customer_id, c.name, c.email
HAVING COUNT(o.order_id) = 0;
Q2: Find employees who earn more than their department’s average salary.
A2:
SELECT e.*
FROM employees e
JOIN (
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id
) dept_avg ON e.department_id = dept_avg.department_id
WHERE e.salary > dept_avg.avg_salary;
Q3: Calculate the total salary expense per manager, including bonus amounts.
A3:
SELECT m.manager_name, SUM(e.salary) + m.bonus AS total_expense
FROM managers m
JOIN departments d ON m.manager_id = d.manager_id
JOIN employees e ON d.department_id = e.department_id
GROUP BY m.manager_name, m.bonus;
Q3: Get the highest and lowest grades for each course.
A3:
SELECT c.title,
MAX(e.grade) AS highest_grade,
MIN(e.grade) AS lowest_grade
FROM courses c
JOIN enrollments e ON c.course_id = e.course_id
GROUP BY c.title;
-- E-commerce Data Analysis with JOINS & Aggregation
Q1: Find the total revenue per customer, including product details.
A1:
SELECT c.name, p.product_name, SUM(oi.quantity * oi.price) AS total_spent
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id
JOIN order_items oi ON o.order_id = oi.order_id
JOIN products p ON oi.product_id = p.product_id
GROUP BY c.name, p.product_name;
Q4: Find customers who purchased products from at least 3 different categories.
A4:
SELECT c.name, COUNT(DISTINCT p.category) AS category_count
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id
JOIN order_items oi ON o.order_id = oi.order_id
JOIN products p ON oi.product_id = p.product_id
GROUP BY c.name
HAVING COUNT(DISTINCT p.category) >= 3;