Home > Database > Mysql Tutorial > How to use avg in mysql

How to use avg in mysql

下次还敢
Release: 2024-05-01 21:16:09
Original
1223 people have browsed it

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>
Copy after login

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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template