2013-04-04 103 views
0

一个人怎么我的表profile_test看起来像这样(列名是在值前面显示):返回平均值和表行的标准方差 - MySQL的

1: profile1_test_1 153.3 
    2: profile1_test_2 152.7 
    3: profile1_test_3 151.5 
    4: profile1_test_4 151.4 
    5: profile1_test_5 151.7 
    6: profile1_test_6 151.8 
    7: profile1_test_7 156.7 
    8: profile1_test_8 157.0 
    9: profile1_test_9 156.8 
    10: profile1_test_10 156.7 

我想知道如何创建一个SQL查询,它将返回每个行的AVGSTD(而不是整列)?数据库是MySQL。我试图做的是跨不同列的平均值(它们是不同测试运行的结果,所以知道它们的平均值和标准差是很有趣的)。

+0

什么是您预期的输出? – 2013-04-04 00:38:59

+0

MySQL有一个内置的'AVG()'聚合函数。但是你真的想跨越不同的列进行平均,而不是多行中的同一列? – Barmar 2013-04-04 00:40:40

+0

@Barmar是的...我试图平均跨越不同的列... – cybertextron 2013-04-04 00:43:01

回答

0

这应该工作:

select rowid, avg(profile_test), stddev(profile_test) 
from (select rowid, 
      (case when n = 1 then profile1_test_1 
        when n = 2 then profile1_test_2 
        . . . 
        when n = 10 then profile1_test_10 
       end) as profile_test 
     from profile_test cross join 
      (select 1 as n union all select 2 union all select 3 union all select 4 union all select 5 union all 
      select 6 union all select 7 union all select 8 union all select 9 union all select 10 
      ) nums 
    ) t 
group by rowid 

有可能是通过编写各行上复杂的算术更有效的方式,但是这应该用于中等大小的数据很好地工作。

0

使用UNION获得在子查询中的所有列到一个列:

select run, avg(val), stddev(val) 
from (select run, profile_test_1 val 
     from mytable 
     union 
     select run, profile_test_2 val 
     from mytable 
     union 
     select run, profile_test_3 val 
     from mytable 
     union 
     ...) x 
group by run 
相关问题