我有这样的桌子:
表名:pelamarmagisterrangkuman
mysql - 如何在SQL中编写四分位数和StDev?-LMLPHP
然后我做了这样的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`

结果是这样的:
mysql - 如何在SQL中编写四分位数和StDev?-LMLPHP
现在,我想找到四分位数和stdev值,但我不知道如何在sql上编写。有人能帮我解决那个问题吗?提前谢谢

最佳答案

标准偏差很容易:

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;

09-27 08:22