SQL -Structured Query Language - Sql Clause - Group By Clause Tutorial
THE ' GROUP BY ' clause is used to group records having similar values. It is used with aggregate functions like count, sum, avg, min, max.
Some of the examples are-
- Calculate the number of employees in each department. (here we will use count()).
- Find the maximum salary of the employee in each department. (here we will use max()).
- Find the minimum salary of the employee in each department. (here we will use min()).
- Calculate the average salary of the employee in each department. (here we will use avg()).
- Calculate the sum of the salary of the employee in each department. (here we will use sum()).
Syntax-
The basic syntax of the GROUP BY statement with aggregate functions like count, sum, avg, min, max.
SELECT function_name(column_name),..,column_name_group
FROM
table_name
GROUP BY
column_name_group;
Here function_name can be count, sum, avg, min, max, and column_name_group is the name of the column to be group by.
For example –
SELECT COUNT(employee_id)
FROM
employees
GROUP BY
department_id;
In this statement, it will Calculate the number of employees in each department. (here we will use count())( Department wise - Group By Department )
SELECT MAX(salary)
FROM
employees
GROUP BY
department_id;
In this statement, it will find the maximum salary of the employee in each department. (here we will use max()).( Department wise - Group By Department )
SELECT MIN(salary)
FROM
employees
GROUP BY
department_id;
In this statement, it will find the minimum salary of the employee in each department. (here we will use min()). ( Department wise - Group By Department )
SELECT AVG(salary)
FROM
employees
GROUP BY
department_id;
In this statement, it will Calculate the average salary of the employee in each department. (here we will use avg()).( Department wise - Group By Department )
SELECT SUM(salary)
FROM
employees
GROUP BY
department_id;
In this statement, it will Calculate the sum of the salary of the employee in each department. (here we will use sum()).( Department wise - Group By Department )