T-SQL Tutorial

T-SQL Aggregate functions


This article describes how to use the T-SQL Aggregate functions in SQL Server database.
Aggregate functions perform a calculation on a set of values and return a single value.
The SQL Server aggregate functions are: AVG, SUM, MAX, MIN, COUNT.

SQL Server Aggregate functions are used to calculate and return the sum, average, minimum, or maximum value of a column in a table. You can also use it to calculate the number of rows in a table or the distinct values in a column.


AVG

The T-SQL AVG function returns the average value.

select avg(price) from courses;
select name, price
from courses
group by name, price
having avg(price) > 70;


SUM

The T-SQL SUM function returns the sum of all values.

select sum(price) from courses;
select sum(price)
from courses
where price > 50;


MAX

The T-SQL MAX function returns the max value.

select max(price) from courses;
select max(price)
from courses
where price < 70;


MIN

The T-SQL MIN function returns the min value.

select min(price) from courses;
select min(price)
from courses
where price > 70;


COUNT

The T-SQL COUNT function returns the number of rows returned by a query.

select count(*) from courses;
select count(*), price
from courses
group by price
having count(*) = 2;