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.
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.
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.
MySQL AVG() Function The AVG() function returns the average value of an expression.
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.
select (A.a + A.b) / 2 from A;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With