Using stddev in Mysql across columns
I have table MYsql table.
name, t1 , t2 , t3.
there many names, and their scores.
Show would calculate the standard deviation of t1,t2,t3
Tried Select name, stddev(t1,t2,t3), it didnt work.
This works:
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
STDEV() is an aggregation function. It takes values from many rows and yields a single result.
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.
Unfortunately, it doesn't take values from several fields. Just several rows, to do that you need to re-work your data to have all the values in a single column...
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
EDIT
Another option, instead of UNION ALL
could be...
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
Try adding GROUP BY name
at the end.
精彩评论