跨列使用Mysql中的stddev

时间:2011-09-14 16:26:12

标签: mysql sql

我有表MYsql表。

name, t1 , t2 , t3. 

有很多名字和他们的分数。

显示将计算t1,t2,t3的标准偏差

尝试选择名称,stddev(t1,t2,t3),它没有用。

这有效:

SELECT
  NAME, STDDEV_SAMP(t)   STD
FROM
( SELECT NAME, t1 AS t FROM test._copy
  UNION ALL 
  SELECT NAME, t2 AS t FROM  test._copy
  UNION ALL
  SELECT NAME, t3 AS t FROM  test._copy
) t
GROUP BY  NAME

2 个答案:

答案 0 :(得分:3)

STDEV()是一个聚合函数。它从多行中获取值并产生单个结果。

SELECT
  name,
  STDEV(t1)   standard_deviation_of_t1,
  STDEV(t2)   standard_deviation_of_t2,
  STDEV(t3)   standard_deviation_of_t3
FROM
  yourTable
GROUP BY
  name

-- This will give meaningful results if there are several records for the
-- same name.

不幸的是,它不会从多个字段中获取值。只需几行,您需要重新处理数据以将所有值都放在一列中......

SELECT
  name,
  STDEV(t)   standard_deviation_of_all_t_values,
FROM
(
  SELECT name, t1 AS t FROM yourTable
  UNION ALL
  SELECT name, t2 AS t FROM yourTable
  UNION ALL
  SELECT name, t3 as t FROM yourTable
)
  AS data
GROUP BY
  name

修改

另一个选项,而不是UNION ALL可能是......

SELECT
  name,
  STDEV(CASE map.field_id WHEN 1 THEN t1 WHEN 2 THEN t2 ELSE t3 END)
FROM
  your_table
CROSS JOIN
  (SELECT 1 as field_id UNION ALL SELECT 2 UNION ALL SELECT 3) AS map
GROUP BY
  name

答案 1 :(得分:0)

尝试在最后添加GROUP BY name