Aggregate Function in SQL


In SQL aggregate function is used to perform calculation on a set of values instead of single value and return single value, in the following example we want to count the total number of employees of a company.

SELECT COUNT(*) AS TotalEmployee
FROM Employee



Now, if we want to know the total number of an employee of each country. If we just add one column of CountryID and run our query let see what happed.
SELECT COUNT(*) AS TotalEmployee, CountryID
FROM Employee


Its mean we need to use Group By clause when we use aggregate function with other columns.
SELECT COUNT(*) TotalEmployee,CountryID
FROM Employee
GROUP BY CountryID

Now if we want to add country name also instead of Country ID, our query looks like.
SELECT COUNT(*) TotalEmployee,C.CountryID,C.CountryName
FROM Employee E
INNER JOIN Country C ON E.CountryID = C.CountryID
GROUP BY C.CountryID, C.CountryName