Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Average of multiple columns

I have a table called Request and the data looks like:

Req_ID    R1   R2   R3   R4   R5  R12673    2    5    3    7    10 R34721    3    5    2    1    8 R27835    1    3    8    5    6 

Now I want to display the average of R1,R2,R3,R4 and R5

So I wrote a query like:

Select Req_ID, Avg(R1+R2+R3+R4+R5) as Average from Request Group by Req_ID 

But I just get the sum of R1,R2,R3,R4 and R5 not the average? Where am I doing wrong.

like image 607
Peter Avatar asked Sep 09 '11 21:09

Peter


People also ask

How do I average multiple columns in Excel?

Click a cell below the column or to the right of the row of the numbers for which you want to find the average. On the HOME tab, click the arrow next to AutoSum > Average, and then press Enter.

How do you find the mean of multiple columns?

To find the mean of multiple columns based on multiple grouping columns in R data frame, we can use summarise_at function with mean function.

How do you average multiple columns in SQL?

In PostgreSQL, to get the average of multiple (2 to 8) columns in one row just define a set of seven functions called average(). Will produce the average of the non-null columns.

How do I average every 5 rows or columns in Excel?

In Excel, have you ever tried to average every 5 rows or columns, that is to say, you need to do these operations: =average (A1:A5), =average(A6:A10), =average(A11:A15),…of course, you can apply the Average function to get the average of every 5 cells every time, but, if there are hundreds and thousands cells in your ...


1 Answers

You don't mention if the columns are nullable. If they are and you want the same semantics that the AVG aggregate provides you can do (2008)

SELECT *,        (SELECT AVG(c)         FROM   (VALUES(R1),                       (R2),                       (R3),                       (R4),                       (R5)) T (c)) AS [Average] FROM   Request   

The 2005 version is a bit more tedious

SELECT *,        (SELECT AVG(c)         FROM   (SELECT R1                 UNION ALL                 SELECT R2                 UNION ALL                 SELECT R3                 UNION ALL                 SELECT R4                 UNION ALL                 SELECT R5) T (c)) AS [Average] FROM   Request 
like image 52
Martin Smith Avatar answered Oct 14 '22 20:10

Martin Smith