SQL GROUP BY
Sure! The GROUP BY
clause in SQL is used to arrange identical data into groups. This is often used with aggregate functions like COUNT()
, SUM()
, AVG()
, MIN()
, and MAX()
to perform calculations on each group of data.
Basic Syntax
SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1;
Example
Let's consider a simple table called Sales
:
ID | Salesperson | Amount |
---|---|---|
1 | Alice | 300 |
2 | Bob | 150 |
3 | Alice | 450 |
4 | Bob | 200 |
5 | Charlie | 300 |
1. Count Sales by Salesperson
To find out how many sales each salesperson has made, you can use:
SELECT Salesperson, COUNT(*) AS NumberOfSales
FROM Sales
GROUP BY Salesperson;
Output:
Salesperson | NumberOfSales |
---|---|
Alice | 2 |
Bob | 2 |
Charlie | 1 |
2. Sum of Sales Amount by Salesperson
To get the total sales amount for each salesperson:
SELECT Salesperson, SUM(Amount) AS TotalSales
FROM Sales
GROUP BY Salesperson;
Output:
Salesperson | TotalSales |
---|---|
Alice | 750 |
Bob | 350 |
Charlie | 300 |
3. Average Sales Amount by Salesperson
To find the average sales amount for each salesperson:
SELECT Salesperson, AVG(Amount) AS AverageSales
FROM Sales
GROUP BY Salesperson;
Output:
Salesperson | AverageSales |
---|---|
Alice | 375.00 |
Bob | 175.00 |
Charlie | 300.00 |
Notes
- When using
GROUP BY
, every column in theSELECT
statement that isn't an aggregate function must be included in theGROUP BY
clause. - You can also use
HAVING
to filter groups based on aggregate functions, which is similar to theWHERE
clause but for groups.
Would you like more details or examples?
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.