简体   繁体   中英

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

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.

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 eg 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

如果没有其他人找到更好的解决方案,您可以随时将它们添加到一起,然后除以您添加的列数。

Not pretty, but it works.

Not specifically MySql, but the idea should be easy enough to translate over.

CREATE TABLE A (id int identity(1,1), C1 int, C2 int, C3 int)
GO

INSERT INTO A VALUES (1,1,1)
INSERT INTO A VALUES (2,2,2)
INSERT INTO A VALUES (3,3,3)
INSERT INTO A VALUES (1,2,3)
INSERT INTO A VALUES (4,5,6)
GO

CREATE VIEW A_Values
AS
SELECT ID, AVG(Val) AS Average 
FROM
(
    SELECT ID, C1 AS Val FROM A
    UNION ALL
    SELECT ID, C2 AS Val FROM A
    UNION ALL
    SELECT ID, C3 AS Val FROM A
) Q
GROUP BY ID
GO


SELECT * FROM A_Values
GO

我不熟悉MySQL语法,但是如何将行数据作为具有单列的多行转储到临时表中,然后使用AVG()函数来获取结果呢?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM