0

I have a table called reviewdb with columns q1,q2,q2.I want to find average of q1,q2 and q3 and store those average values in rows. please help me.

q1 q2 q3
5  4  2
4  3  2
4  5  1

find avg of q1,q2, q3 and store avg of q1 in a row and avg of q2 in another row and avg of q3 in the next row.
q  average
q1  4.3
q2  4
q3  1.6

3 Answers 3

2
select 'q1' as q, avg(q1) avrg from yourtable

union all  

select 'q2', avg(q2) from yourtable

union all 

select 'q3', avg (q3) from yourtable
Sign up to request clarification or add additional context in comments.

Comments

1

One method is a simple union all:

select 'q1' as q, avg(q1) as average from t
union all
select 'q2' as q, avg(q2) as average from t
union all
select 'q3' as q, avg(q3) as average from t;

Comments

1
Select q 
      ,AVG(CAST(Vals AS DECIMAL(10,2))) Average
from tableName  
  UNPIVOT (vals for q in (q1,q2,q3))up
Group by q

or to get two decimal places

Select q 
      ,CAST(AVG(CAST(Vals AS DECIMAL(10,2)) )AS DECIMAL(10,2)) Average
from @t 
  UNPIVOT (vals for q in (q1,q2,q3))up
Group by q

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.