T-SQL Tutorial

How to use Having 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 greater than two and group by department

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

Results

EMP_NODEPT_ID
520

Select the salary with having

SELECT ID, SAL
FROM EMPLOYEES
GROUP BY ID, SAL
HAVING SUM(SAL) >= 3000;

Results

IDSAL
13000.00
23000.00
105000.00