SQL Questions
SQL Questions
11. Retrieve the top 5 customers with the highest total purchase amount:
SELECT customer_id, SUM(amount) AS total_purchase_amount
FROM Orders
GROUP BY customer_id
ORDER BY total_purchase_amount DESC
LIMIT 5;
12. List the names of all customers who have made at least 3 orders:
SELECT customer_name
FROM Customers
WHERE customer_id IN (
SELECT customer_id
FROM Orders
GROUP BY customer_id
HAVING COUNT(*) >= 3
);
18. Find employees who have the same salary as their colleagues:
SELECT
e1.employee_id,
e1.employee_name,
e1.salary
FROM
Employee e1
JOIN
Employee e2 ON e1.salary = e2.salary
AND e1.employee_id <> e2.employee_id
AND e1.department = e2.department
WHERE
e1.employee_id < e2.employee_id;
19. List the employees who have been with the company for more than 5 years:
SELECT * FROM Employee WHERE DATEDIFF(YEAR, join_date, GETDATE()) > 5;
22. Find the customer who has placed the highest number of orders:
SELECT customer_id, COUNT(*) AS num_orders
FROM Orders
GROUP BY customer_id
ORDER BY num_orders DESC
LIMIT 1;
29. Retrieve the average time taken to ship orders for each shipping method:
SELECT shipping_method, AVG(DATEDIFF(DAY, order_date, ship_date)) AS
avg_shipping_time
FROM Orders
GROUP BY shipping_method;
30. Find the total number of unique customers who made purchases in each year:
SELECT EXTRACT(YEAR FROM order_date) AS year, COUNT(DISTINCT customer_id) AS
num_customers
FROM Orders
GROUP BY EXTRACT(YEAR FROM order_date);
32. Find the average salary difference between employees and their managers:
SELECT AVG(e.salary - m.salary) AS avg_salary_difference
FROM Employee e
JOIN Employee m ON e.manager_id = m.employee_id;
33. List customers who have spent more than the average total amount spent by all
customers:
SELECT customer_id, SUM(amount) AS total_spent
FROM Orders
GROUP BY customer_id
HAVING SUM(amount) > (SELECT AVG(total_amount) FROM (SELECT SUM(amount) AS
total_amount FROM Orders GROUP BY customer_id) AS avg_amount);
34. Retrieve the top 5 categories with the highest average sales amount:
SELECT category, AVG(amount) AS avg_sales_amount
FROM Products
GROUP BY category
ORDER BY avg_sales_amount DESC
LIMIT 5;
37. Retrieve the top 3 most recent orders for each customer:
SELECT customer_id, order_id, order_date
FROM (
SELECT customer_id, order_id, order_date,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC) AS rank
FROM Orders
) AS ranked_orders
WHERE rank <= 3;
38. List the customers who have placed orders in all categories:
SELECT customer_id
FROM Orders
GROUP BY customer_id
HAVING COUNT(DISTINCT category_id) = (SELECT COUNT(DISTINCT category_id) FROM
Products);
40. Find the products that have been sold every month for the past year:
SELECT product_id
FROM Sales
GROUP BY product_id
HAVING COUNT(DISTINCT EXTRACT(MONTH FROM sale_date)) = 12;