Collections:
AVG() - Average Value in Group
How to calculate the average value of a field expression in result set groups using the AVG() function?
✍: FYIcenter.com
AVG(expr) is a MySQL built-in aggregate function that
calculates the average value of a field expression in result set groups.
For example:
SELECT help_category_id, AVG(help_topic_id), COUNT(help_topic_id) FROM mysql.help_topic GROUP BY help_category_id; -- +------------------+--------------------+----------------------+ -- | help_category_id | AVG(help_topic_id) | COUNT(help_topic_id) | -- +------------------+--------------------+----------------------+ -- | 1 | 0.5000 | 2 | -- | 2 | 21.9143 | 35 | -- | 3 | 635.5932 | 59 | -- | 4 | 4.5000 | 2 | -- | 5 | 42.3333 | 3 | -- ... -- +------------------+--------------------+----------------------+ SELECT help_category_id, help_topic_id FROM mysql.help_topic WHERE help_category_id = 5; -- +------------------+---------------+ -- | help_category_id | help_topic_id | -- +------------------+---------------+ -- | 5 | 40 | -- | 5 | 43 | -- | 5 | 44 | -- +------------------+---------------+
AVG() is also a window function, you can call it with the OVER clause to calculate the average value of the given expression in the current window. For example:
SELECT help_topic_id, help_category_id, AVG(help_topic_id) OVER w FROM mysql.help_topic WINDOW w AS (PARTITION BY help_category_id); -- +---------------+------------------+---------------------------+ -- | help_topic_id | help_category_id | AVG(help_topic_id) OVER w | -- +---------------+------------------+---------------------------+ -- | 0 | 1 | 0.5000 | -- | 1 | 1 | 0.5000 | -- | 2 | 2 | 21.9143 | -- | 6 | 2 | 21.9143 | -- | 7 | 2 | 21.9143 | -- ... -- +---------------+------------------+---------------------------+
Reference information of the AVG() function:
AVG(DISTINCT expr): avg Returns the average value of expr. The DISTINCT option can be used to return the average of the distinct values of expr. Arguments, return value and availability: expr: Required. The field expression in result set groups. DISTINCT: Optional. If provided, only distinct values of expr are used. avg: Return value. The average value of the input expression. Available since MySQL 4.
Related MySQL functions:
⇒ BIT_AND() - Bitwise AND in Group
⇐ ANY_VALUE() - Any Value in Group
2023-11-18, 1112🔥, 0💬
Popular Posts:
How to download Microsoft SQL Server 2005 Express Edition in SQL Server? Microsoft SQL Server 2005 E...
Where to find answers to frequently asked questions on INSERT, UPDATE and DELETE Statements in MySQL...
What is test testing area for? The testing area is provided to allow visitors to post testing commen...
How To Generate Random Numbers with the RAND() Function in SQL Server Transact-SQL? Random numbers a...
How To Update Multiple Rows with One UPDATE Statement in SQL Server? If the WHERE clause in an UPDAT...