Posted by : Glen Sajori Sabtu, 27 September 2014

Description

The SQL AVG function is used to return the average of an expression in a SELECT statement.


Syntax

The syntax for the SQL AVG function is:

SELECT AVG(expression)
FROM tables
WHERE conditions;

Parameters or Arguments

expression can be a numeric field or formula.

Example - With Single Expression

For example, you might wish to know how the average cost of all products that are in the Clothing category.

SELECT AVG(cost) AS "Average Cost"
FROM products
WHERE category = 'Clothing';
 
In this SQL AVG Function example, we've aliased the AVG(cost) expression as "Average Cost". As a result, "Average Cost" will display as the field name when the result set is returned.

Example - Using SQL DISTINCT

You can use the SQL DISTINCT clause within the AVG function. For example, the SELECT statement below returns the combined average cost of unique cost values where the category is Clothing.

SELECT AVG(DISTINCT cost) AS "Average Cost"
FROM products
WHERE category = 'Clothing';
 
If there were two cost values of $25, only one of these values would be used in the AVG function calculation.

Example - Using Formula

The expression contained within the AVG function does not need to be a single field. You could also use a formula. For example, you might want the average profit for a product. Average profit is calculated as sale_price less cost.

SELECT AVG(sale_price - cost) AS "Average Profit"
FROM products;

You might also want to perform a mathematical operation within the AVG function. For example, you might determine the average commission as 10% of sale_price.
 
SELECT AVG(sale_price * 0.10) AS "Average Commission"
FROM products;

Example - Using SQL GROUP BY

In some cases, you will be required to use the SQL GROUP BY clause with the AVG function.
For example, you could also use the AVG function to return the name of the department and the average sales (in the associated department).
SELECT department, AVG(sales) AS "Average Sales"
FROM order_details
GROUP BY department;
Because you have listed one column in your SELECT statement that is not encapsulated in the AVG function, you must use the GROUP BY clause. The department field must, therefore, be listed in the GROUP BY section.

Source : techonthenet.com

Leave a Reply

Subscribe to Posts | Subscribe to Comments

Translate to Your Language

STMIK AMIKOM YOGYAKARTA

Followers

✠Ulquίoґґ∆✠. Diberdayakan oleh Blogger.

Copyright © Free Download+§hare Anything That You Want -Black Rock Shooter- Powered by Blogger - Designed by Johanes Djogan