将月份拆分为4并检索每天的平均值

时间:2018-05-28 09:21:24

标签: php mysql sql date stored-procedures

这是在MySQL中的复杂存储过程中创建的临时表上的查询输出:

enter image description here

现在的目标是像我们这里一样拥有每天的平均持续时间,但是按月计算每周

因此,我希望每个月都将划分为4天天数,平均持续时间每天
因此,无论这个月有多少天,我都会有4个值。

我该怎么做?

注意:如果更容易,我可以使用php,因为我会使用这种语言的数据。

1 个答案:

答案 0 :(得分:2)

您有一个每天分组的查询,例如:

select 
  the_date as day,
  sec_to_time(avg(timestampdiff(second, start_time, end_time))) as duration
from ...
group by the_date;

您希望每月1-7,8-14,15-21,22-月。使用CASE WHEN构建组。

select 
  year(the_date) as year,
  month(the_date) as month,
  case 
    when day(the_date) <=  7 then '01-07'
    when day(the_date) <= 14 then '08-14'
    when day(the_date) <= 21 then '15-21'
    else                          '22-end'
  end as day_range,
  sec_to_time(avg(timestampdiff(second, start_time, end_time))) as duration
from ...
group by year, month, day_range
order by year, month, day_range;