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 the SELECT
statement that isn't an aggregate function must be included in the GROUP BY
clause.
- You can also use
HAVING
to filter groups based on aggregate functions, which is similar to the WHERE
clause but for groups.
Would you like more details or examples?