Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL query: How to calculate the average of values in a row?

Tags:

mysql

The AVG() function calculates column-means but how can I retrieve the mean of several values in the same row like so:

SELECT MEAN(A.a, A.b, ... , A.n) FROM A;

EDIT: sure, as cherouvim suggests I can do:

SELECT MEAN(A.a + A.b + ... + A.n) / n FROM A;

but I'm trying to find out if there's a leaner way.

like image 701
markus Avatar asked Apr 02 '09 18:04

markus


People also ask

How do I find the average of a row in MySQL?

MySQL AVG() function with DISTINCT clause MySQL uses the DISTINCT keyword to remove the duplicate rows from the column name. This clause is used with this avg() function to return the average value of a unique number of records present in the table.

How do I find the average of each row in SQL?

The AVG function finds the arithmetic mean for a group of records in a SQL table. An average, or arithmetic mean, is the sum of a group of numbers divided by the count for that group. For example, 2+4+4+6+6+8 is 30 divided 6 which results in an average of 5.

How do you calculate average in MySQL?

MySQL AVG() Function The AVG() function returns the average value of an expression.

How do I find the average of a group in MySQL?

Example: MySQL AVG() function with group byMySQL AVG() function retrieves the average value of a given expression for each group if it is used with group by option. The following statement will return the average number of pages for each group of 'pub_id' from book_mast table.


2 Answers

select (A.a + A.b) / 2 from A;
like image 98
cherouvim Avatar answered Oct 19 '22 12:10

cherouvim


I stumbled upon a similar situation. This came useful: http://tech-blog.borychowski.com/index.php/2009/02/mysql/average-value-in-a-row/

From the page:

When we do:

SELECT *, (V.rank_0 + V.rank_1 + V.rank_2) / 3
AS row_avg FROM voting V

we only receive correct averages for the rows where all values are not NULL. But when I have e.g. 3, NULL, 4 I’d like to get 3.5 as a return. That’s the moment when function COALESCE() comes handy.

What does COALESCE () do? From MySQL manual we have:

Returns the first non-NULL value in the list, or NULL if there are no non-NULL values.

mysql> SELECT COALESCE(NULL,1);
-> 1
mysql> SELECT COALESCE(NULL,NULL,NULL);
-> NULL

And these information will help us to build another SELECT statement:

SELECT *,

#first part
(COALESCE(V.rank_0, 0)
+ COALESCE(V.rank_1, 0)
+ COALESCE(V.rank_2, 0))
/

#second part
(3 -
(COALESCE(V.rank_0 - V.rank_0, 1)
+ COALESCE(V.rank_1 - V.rank_1, 1)
+ COALESCE(V.rank_2 - V.rank_2, 1))
) AS row_avg FROM voting V
like image 27
Pratyush Avatar answered Oct 19 '22 12:10

Pratyush