Search code examples
sqldatabasepostgresqlaverage

Average of two columns in SQL


I wanted to take average of two columns and display in a new column something like this:

+-+--+--+--+--------+--------+
|A|B |C |D |AVG(B/C)|AVG(C/B)|
+-+--+--+--+--------+--------+
|S|23|34|56|        |        |
+-+--+--+--+--------+--------+
|T|45|6 |79|        |        |
+-+--+--+--+--------+--------+

So, as shown above, I needed to take the each row values and perform B/C and then take the average accordingly to display it in a new column.

I wanted to do this in SQL query. Is it possible to perform this in a SQL command? I know the AVG() function does take the average of a column but how can I do B/C and then take the average? also if I need to take the average of B and C as well how can i do that.

This is what I am doing right now:

Select A,B,C,D FROM tableTest where A='S';

I now have to take the average of corresponding and also have another two columns additionally in the query to show the respective results.


Solution

  • You should give it a try:

    SELECT A, AVG((B+C)/2) as bc, AVG((C+B)/2) as cb
    FROM tableTest
    WHERE A = 'S'
    GROUP BY A