T-SQL Tutorial

How to use Group By clause in a query


Example

Employees table

IDMANAGER_IDSALDEPT_ID
18300020
28300020
3180020
4795030
52110020
69130010
710285030
810297520
910245010
10NULL500010




Count the number of employees group by department

SELECT COUNT(ID) EMP_NO, DEPT_ID
FROM EMPLOYEES
WHERE MANAGER_ID IS NOT NULL
GROUP BY DEPT_ID;

Results

EMP_NODEPT_ID
210
520
230

Select the sum of salary group by department

SELECT DEPT_ID, SUM(SAL) SAL_SUM
FROM EMPLOYEES
GROUP BY DEPT_ID;

Results

DEPT_IDSAL_SUM
108750.00
2010875.00
303800.00