tags:

views:

521

answers:

4

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.

+3  A: 
select (A.a + A.b) / 2 from A;
cherouvim
well, I need it more generic, meaning for x vars.
tharkun
Surely you'll always know the number or columns for a given table?
Tom Wright
@tharkun: does this mean that you'll be selecting X columns and you don't know X? what are you trying to accomplish?
cherouvim
sure I can count how many columns I'm selecting and use that count for the division... with my question I'm just trying to find out, if there's a function for that...
tharkun
I doubt there would be a function for that. As it is , it's not difficult to achieve. The harder part is coming up with a scenario where it can be used :)
Learning
A: 

If no one else finds a better solution, you could always just add them together, then divide by the number of columns you added.

AaronLS
A: 

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
beach
interesting but not mysql and not leaner ;)
tharkun
A: 

I'm not familiar with the MySQL syntax, but what about dumping the row data into a temporary table as multiple rows with a single column, and then using the AVG() function to obtain your result?

patjbs