我想计算MySQL中给定月份前6个月的平均值

时间:2018-03-26 00:21:22

标签: php mysql average

imgur

示例代码:

SELECT Avg(dt.number_of_employees)
FROM   (SELECT number_of_employees
        FROM   my_table
        ORDER  BY date DESC
        LIMIT  1, 6) dt;

但没有奏效。我怎么用ph​​p计算?

2 个答案:

答案 0 :(得分:0)

你不需要PHP来计算,MySQL会做得很好:

1.000000 + 1.000000

答案 1 :(得分:0)

这是有效的,如本演示所示:http://sqlfiddle.com/#!9/b17749/1

set @rownum := 0;
set @rownum2 := 0;
set @lastrownum := (select count(*) from my_table); 
select date,
       number_of_employees,
       sum(number_of_employees)/(maxrownum-rnum+1) as avg_per_6months,
       round(sum(number_of_employees)/(maxrownum-rnum+1),0) as avg_rounded
from (
 select t.date, 
     t.number_of_employees,
      s.rnum,
      s.maxrownum,
      t.rnum2
   from (
select date,   
(@rownum := @rownum + 1) as rnum,
(case when @lastrownum <= @rownum + 5  then @lastrownum 
      else (@rownum + 5) end) as maxrownum
from my_table
order by date desc) s
cross join (
select date, number_of_employees, 
(@rownum2 := @rownum2 + 1) as rnum2 
from my_table
order by date desc) t ) v 
where rnum2 between rnum and maxrownum
group by rnum
order by rnum, rnum2