The AVG()
function in SQL Server is used to calculate the average value of a numeric column. It is an aggregate function, meaning it operates on a set of values and returns a single value.
Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;
Key Points:
- Numeric Data: The column used in the
AVG()
function must contain numeric data types, such asINT
,FLOAT
,DECIMAL
, etc. - NULL Values:
AVG()
ignoresNULL
values in the calculation. - Grouping: It can be combined with the
GROUP BY
clause to calculate averages for groups of rows.
Example 1: Simple Average
To calculate the average price of products:
SELECT AVG(Price) AS AveragePrice
FROM Products;
Example 2: Using a Condition
To calculate the average price of products costing more than $50:
SELECT AVG(Price) AS AveragePrice
FROM Products
WHERE Price > 50;
Example 3: Grouped Averages
To calculate the average price of products by category:
SELECT CategoryID, AVG(Price) AS AveragePrice
FROM Products
GROUP BY CategoryID;
Example 4: Combining with Other Aggregate Functions
To calculate the total and average price of products:
SELECT SUM(Price) AS TotalPrice, AVG(Price) AS AveragePrice
FROM Products;
The AVG()
function is straightforward and highly useful for summarizing numerical data in SQL queries.
No comments:
Post a Comment