id product region quantity price
1 Pen North 10 5
2 Pencil South 20 2
3 Pen North 15 5
4 Eraser East 30 1
5 Pencil South 25 2
6 Pen East 5 5
CREATE TABLE sales (
id INT PRIMARY KEY,
product VARCHAR(50),
region VARCHAR(50),
quantity INT,
price DECIMAL(10, 2)
);
INSERT INTO sales (id, product, region, quantity, price) VALUES
(1, 'Pen', 'North', 10, 5.00),
(2, 'Pencil', 'South', 20, 2.00),
(3, 'Pen', 'North', 15, 5.00),
(4, 'Eraser', 'East', 30, 1.00),
(5, 'Pencil', 'South', 25, 2.00),
(6, 'Pen', 'East', 5, 5.00);
GROUP BY to get total quantity sold per product
SELECT product, SUM(quantity) AS total_quantity
FROM sales
GROUP BY product;
GROUP BY multiple columns: product and region
SELECT product, region, SUM(quantity) AS total_quantity
FROM sales
GROUP BY product, region;
GROUP BY with HAVING: Show products with total quantity > 30
SELECT product, SUM(quantity) AS total_quantity
FROM sales
GROUP BY product
HAVING total_quantity > 30;
GROUP BY with AVG and HAVING
SELECT region, AVG(quantity) AS avg_quantity
FROM sales
GROUP BY region
HAVING avg_quantity >= 20;
Using COUNT with GROUP BY and HAVING
SELECT product, COUNT(*) AS num_sales
FROM sales
GROUP BY product
HAVING num_sales > 1;