如何在sqlserver中将列转换为行

时间:2015-11-26 22:07:27

标签: sql-server

我有一个名为reviewdb的表,列q1,q2,q2。我想找到q1,q2和q3的平均值,并将这些平均值存储在行中。请帮帮我。

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 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

一种方法是简单的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;

答案 2 :(得分: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

或获得两位小数

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