SQL - Group By
SQL – ‘GROUP BY’ clause allows you to grouped the rows together.
- The groups are determined by the columns that you specify in the GROUP BY clause.
- It is often used with aggregate functions (COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by one or more columns.
SELECT select_list FROM table_name GROUP BY column_name1, column_name2 ,...;
Consider Employee table having below records.
To retrieve the total loan-amount of all loans taken by each Employee.
SELECT EmployeeID, SUM(LoanAmount) FROM Employee_Loan. GROUP BY EmployeeID;
Find out the total no of employees in each departments
SELECT DepartmentID, COUNT(EmployeeID) FROM Employee GROUP BY DepartmentID;