2013-04-04 105 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 
相關問題