SQL Server Aggregate Functions – SUM, COUNT, MAX, MIN, AVG

SQL aggregate functions AVG, COUNT, MAX, MIN, SUM are used the most. That is because we often need to add, make average or find the highest or lowest value.

It is mandatory to use GROUP BY clause anytime when we use aggregate function.  (except for operations over windows using OVER())

List of SQL Server Aggregate Functions

AVG() – returns average value from the table
COUNT() – returns number of rows (values)
MAX() – returns maximal (highest) value
MIN() – returns minimal (lowest) value
SUM() – returns total of values

The combination of the aggregation function and the GROUP BY clause allows data to be aggregated (for example, in the GROUP BY article), this is important in order to reduce the atomicity of the data.

Example

Let’s have a table with Sales [SalesAmount] and date of order [OrderDate].

aggregate functions example

We will apply all aggregate functions on the sales column. It can be seen well on this example:

SELECT
  CAST(OrderDate AS DATE) AS OrderDate,
  SUM(SalesAmount)        AS Total_Sales,
  AVG(SalesAmount)        AS Average_Sales,
  COUNT(SalesAmount)      AS Count_Sales,
  MAX(SalesAmount)        AS Max_Sale,
  MIN(SalesAmount)        AS Min_Sale
FROM AdventureWorksDW2014.dbo.FactInternetSales
GROUP BY OrderDate
ORDER BY OrderDate;

sql aggregate functions example - sum,avg,min,max,count

Rate this post
Category: SQL Functions

About Ing. Jan Zedníček - Data Engineer & Controlling

My name is Jan Zednicek, and I have been working as a freelance Data Engineer for roughly 10 years. During this time, I have been publishing case studies and technical guides on this website, targeting professionals, students, and enthusiasts interested in Data Engineering particularly on Microsoft technologies as well as corporate finance and reporting solutions. 🔥 If you found this article helpful, please share it or mention me on your website or Community forum

Leave a Reply

Your email address will not be published. Required fields are marked *