Aggregate functions are SQL functions that return a single value based on multiple rows of a table. They can be used to perform calculations on entire sets of data rather than individual rows. SQL Server provides several built-in aggregate functions like COUNT, SUM, AVG, MAX, and MIN.
Here are some examples of these aggregate functions in action:
1. COUNT: This function counts the number of rows in a table based on a given condition.
SELECT COUNT(*) FROM orders;
This SQL statement returns the total number of orders.
2. SUM: This function returns the sum of a numerical column in a table.
SELECT SUM(price) FROM products WHERE category = 'electronics';
This SQL statement returns the total price of all electronic products.
3. AVG: This function returns the average value of a numerical column in a table.
SELECT AVG(age) FROM employees WHERE department = 'sales';
This SQL statement returns the average age of all employees in the sales department.
4. MAX: This function returns the maximum value of a column in a table.
SELECT MAX(salary) FROM employees WHERE title = 'manager';
This SQL statement returns the highest salary among all managers.
5. MIN: This function returns the minimum value of a column in a table.
SELECT MIN(quantity) FROM orders WHERE product_id = 123;
This SQL statement returns the smallest quantity of product with ID 123 that was ordered.
Aggregate functions can also be combined with other SQL statements like GROUP BY to group and summarize data by certain criteria. In conclusion, aggregate functions are powerful tools for summarizing large sets of data in SQL Server.