SQL_Aggregations & Grouping
SQL_Aggregations & Grouping
1. Calculate the total quantity and total amount for each order.
SELECT
o.order_id,
SUM(oi.quantity) AS total_quantity,
SUM(oi.amount) AS total_amount
FROM
Orders o
LEFT JOIN
Order_Items oi ON o.order_id = oi.order_id
GROUP BY
o.order_id;
2. Find the average age and the number of employees for each job title.
SELECT
job_title,
AVG(age) AS average_age,
COUNT(*) AS number_of_employees
FROM
Employees
GROUP BY
job_title;
SELECT
c.category_name,
COUNT(p.product_id) AS total_products
FROM
Categories c
LEFT JOIN
Products p ON c.category_id = p.category_id
GROUP BY
c.category_name;
SELECT
p.product_name,
AVG(r.rating) AS average_rating,
COUNT(r.review_id) AS number_of_reviews
FROM
Products p
LEFT JOIN
Reviews r ON p.product_id = r.product_id
GROUP BY
p.product_id, p.product_name;
5. Find the customers with the highest and lowest total order amounts.
WITH CustomerTotals AS (
SELECT
c.customer_id,
c.customer_name,
SUM(o.order_amount) AS total_order_amount,
RANK() OVER (ORDER BY SUM(o.order_amount) DESC) AS rank_desc,
RANK() OVER (ORDER BY SUM(o.order_amount) ASC) AS rank_asc
FROM
Customers c
LEFT JOIN
Orders o ON c.customer_id = o.customer_id
GROUP BY
c.customer_id, c.customer_name
)
SELECT
customer_id,
customer_name,
total_order_amount
FROM
CustomerTotals
WHERE
rank_desc = 1
OR
rank_asc = 1;
___________________________________________________________________________________
WITH CustomerTotals AS (
SELECT
c.customer_id,
c.customer_name,
SUM(o.order_amount) AS total_order_amount
FROM
Customers c
JOIN
Orders o ON c.customer_id = o.customer_id
SELECT
department,
MAX(age) AS max_age,
MIN(age) AS min_age
FROM
Employees
GROUP BY
department;
7. Calculate the total sales amount and the number of orders for each month.
SELECT
YEAR(order_date) AS order_year,
MONTH(order_date) AS order_month,
SUM(order_amount) AS total_sales_amount,
COUNT(*) AS number_of_orders
FROM
Orders
GROUP BY
YEAR(order_date), MONTH(order_date)
ORDER BY
order_year, order_month;
SELECT
s.supplier_id,
s.supplier_name,
AVG(p.price) AS average_price,
COUNT(*) AS number_of_products
FROM
Suppliers s
LEFT JOIN
Products p ON s.supplier_id = p.supplier_id
GROUP BY
s.supplier_id, s.supplier_name
ORDER BY
s.supplier_id;
9. Get the maximum and minimum prices for each product category.
SELECT
c.category_id,
c.category_name,
MAX(p.price) AS max_price,
MIN(p.price) AS min_price
FROM
Categories c
LEFT JOIN
Products p ON c.category_id = p.category_id
GROUP BY
c.category_id, c.category_name
ORDER BY
c.category_id;
10. Calculate the average rating and the number of reviews for each product category.