Aggregate Functions in SQL
What are Aggregate Functions?
Aggregate functions are SQL functions that operate on a set of values to return a single value. They are useful for summarizing data and performing calculations on groups of rows.
Common Aggregate Functions
- COUNT(): Counts the number of rows in a group.
- SUM(): Calculates the sum of values in a column.
- AVG(): Calculates the average of values in a column.
- MIN(): Finds the minimum value in a column.
- MAX(): Finds the maximum value in a column.
Example
Let's say you have a table named 'Orders' with columns like 'OrderID', 'CustomerID', and 'OrderAmount'. You want to calculate the total order amount for each customer.
SELECT CustomerID, SUM(OrderAmount) AS TotalOrderAmount
FROM Orders
GROUP BY CustomerID;
Grouping with Aggregate Functions
Aggregate functions are often used in conjunction with the `GROUP BY` clause. The `GROUP BY` clause groups rows based on one or more columns, allowing you to apply aggregate functions to each group.