Home  >  Article  >  Database  >  How to use avg in mysql

How to use avg in mysql

下次还敢
下次还敢Original
2024-05-01 21:16:091174browse

MySQL’s AVG() function is used to calculate the average of numeric values. It supports a variety of usages, including: Calculate the average quantity of all sold products: SELECT AVG(quantity_sold) FROM sales; Calculate the average price: AVG(price); Calculate the average sales volume: AVG(quantity_sold * price). The AVG() function ignores NULL values, use IFNULL() to calculate the average of non-null values.

How to use avg in mysql

Usage of AVG() function in MySQL

The AVG() function is used to calculate a set of numeric values average value. It is an aggregate function, which means it aggregates values ​​from a set of rows into a single result.

Syntax:

<code class="sql">AVG(expression)</code>

Where:

  • expression is the target column or expression to calculate the average .

Usage example:

Suppose we have a table named "sales" with the following columns:

  • id (primary key)
  • product_name
  • quantity_sold
  • price

#To calculate the average quantity of all products sold, we can use the following query:

<code class="sql">SELECT AVG(quantity_sold) FROM sales;</code>

The result will be a single row containing the average quantity value.

Other uses:

The AVG() function can also be used to calculate other types of averages, such as:

  • Average price: AVG(price)
  • Average sales: AVG(quantity_sold * price)

Notes:

  • AVG() function ignores NULL values.
  • If expression contains only NULL values, the AVG() function will return NULL.
  • To calculate the average of non-null values, you can use AVG(IFNULL(expression, 0)).

The above is the detailed content of How to use avg in mysql. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn