Postgres多列的标准偏差

时间:2015-12-05 16:01:12

标签: sql postgresql

我正在尝试计算每个给定ID的多列的标准偏差。

我有一张表格显示随着时间的推移给我的需求,我需要计算需求的波动性。

SELECT id ::Text, n0 ::numeric, n1 ::numeric, n2 ::Numeric, n3 ::numeric, n4 ::numeric, n5 ::numeric, n6 ::numeric, n7 ::numeric  
FROM mytable

我想添加另一个列,用于计算每个n0-n7id中值的标准偏差。

3 个答案:

答案 0 :(得分:1)

要使用stddev_pop()聚合函数,您应该将值收集到数组中,然后在unnest()数组中收集:

select id, stddev_pop(val)
from (
    select id, unnest(array[n0, n1, n2, n3, n4, n5, n6, n7]) val
    from mytable
    ) sub
group by id;

答案 1 :(得分:1)

嗯。可能最简单的方法是取消表格并重新聚合。例如:

select id, stddev(n)
from ((select id, n0 as n from mytable) union all
      (select id, n1 as n from mytable) union all
      (select id, n2 as n from mytable) union all
      (select id, n3 as n from mytable) union all
      (select id, n4 as n from mytable) union all
      (select id, n5 as n from mytable) union all
      (select id, n6 as n from mytable) union all
      (select id, n7 as n from mytable)
     ) t
group by id;

注意:您可以选择stddev_pop()stddev_samp()。后者将是这个问题的典型选择。

答案 2 :(得分:0)

你试过stddev_samp吗?或者您的意思是列之间的标准偏差?如果是这样,请查看this SO question