

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


An aggregate function allows you to perform a calculation on a set of values to return a single scalar value. We often use aggregate functions with the GROUP BY and HAVING clauses of the SELECT statement.
The following are the most commonly used SQL aggregate functions:
Group by clause is used to group a selected set of rows into a set of summary rows by the values of one or more columns or expressions. It is always used in conjunction with one or more aggregate functions.
I want an sql query, which gives total salaries paid by City. The output should be as shown below.
Query for retrieving total salaries by city : We are applying SUM() aggregate function on Salary column, and grouping by city column. This effectively adds, all salaries of employees with in the same city.
Select City, SUM(Salary) as TotalSalary
from tblEmployee Group by City
Note: If you omit, the group by clause and try to execute the query, you get an error - Column 'tblEmployee.City' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Now, I want an sql query, which gives total salaries by City, by gender. The output should be as shown below.
Query for retrieving total salaries by city and by gender : It's possible to group by multiple columns. In this query, we are grouping first by city and then by gender.
Select City, Gender, SUM(Salary) as TotalSalary from tblEmployee group by City, Gender
Now, I want an sql query, which gives total salaries and total number of employees by City, and by gender. The output should be as shown below.
Query for retrieving total salaries and total number of employees by City, and by gender : The only difference here is that, we are using Count() aggregate function.
Select City, Gender, SUM(Salary) as TotalSalary, COUNT(ID) as TotalEmployees from tblEmployee group by City, Gender
Filtering Groups: WHERE clause is used to filter rows before aggregation, where as HAVING clause is used to