返回表行的平均值和std偏差 - MySQL

时间:2013-04-04 00:37:02

标签: mysql

我的表格profile_test如何看起来像这样(列名显示在值的前面):

  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。我要做的是不同列的平均值(它们是不同测试运行的结果,所以知道它们的avg和std很有意思。)

2 个答案:

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

通过在每一行上编写复杂的算法,可能有一种更有效的方法,但这对于适度的数据大小应该很有效。

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