0% found this document useful (0 votes)
24 views2 pages

Groupby and Having

The document outlines the creation of a sales table and the insertion of various product sales data. It includes SQL queries for grouping sales data by product and region, calculating total quantities, averages, and counts, as well as applying conditions using HAVING. This provides insights into sales performance across different products and regions.

Uploaded by

sathiya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views2 pages

Groupby and Having

The document outlines the creation of a sales table and the insertion of various product sales data. It includes SQL queries for grouping sales data by product and region, calculating total quantities, averages, and counts, as well as applying conditions using HAVING. This provides insights into sales performance across different products and regions.

Uploaded by

sathiya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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;

You might also like