如何在SQL中编写四分位数和StDev?

时间:2017-05-11 02:23:01

标签: mysql sql phpmyadmin

我有这样的表:

表格的名称: pelamarmagisterrangkuman

enter image description here

然后我做了这样的sql来找到平均值,最小值,最大值

select `pelamarmagisterrangkuman`.`major` AS `ProgramStudi`,
count(usia) as N,
AVG(usia) as Mean,
MIN(usia) as Minimum,
MAX(usia) as Maximum
from `pelamarmagisterrangkuman` group by `pelamarmagisterrangkuman`.`major`

结果是这样的:

enter image description here

现在,我想找到四分位数和stdev值,但我不知道如何在sql上写。有人可以帮我解决这个问题吗?提前致谢

1 个答案:

答案 0 :(得分:1)

标准差很容易:

select p.major AS ProgramStudi,
       count(usia) as N, AVG(usia) as Mean,
       MIN(usia) as Minimum, MAX(usia) as Maximum,
       STDDEV(usia)
from `pelamarmagisterrangkuman` p
group by p.major;

四分位数要难得多。我认为最可靠的方法可能是使用变量:

select p.major AS ProgramStudi,
       count(usia) as N, AVG(usia) as Mean,
       MIN(usia) as Minimum, MAX(usia) as Maximum,
       STDDEV(usia) as stddev,
       max(case when floor(0.25*pp.cnt) = rn then usia end) as quartile_1,
       max(case when floor(0.50*pp.cnt) = rn then usia end) as quartile_2,
       max(case when floor(0.75*pp.cnt) = rn then usia end) as quartile_3
from (select p.*,
             (@rn := if(@m = p.major, @rn + 1,
                        if(@m := p.major, 1, 1)
                       )
             ) as rn
      from pelamarmagisterrangkuman p cross join
           (select @m := '', @rn := 0) params
      order by p.major, p.usia
     ) p join
     (select p.major, count(*) as cnt
      from pelamarmagisterrangkuman p
      group by p.major
     ) pp
     on p.major = pp.major
group by p.major;