下表几乎每分钟都通过cronjob接收一个数据集:

id  |  timestamp  | humanTime          | userCount
-----------------------------------------------------
1      1482310202   2016-12-21 09:50:07   120
2      1482310262   2016-12-21 09:51:07   126
3      1482310322   2016-12-21 09:52:06   110
4      1482310381   2016-12-21 09:54:06   131
5      ...

由于cronjob是通过网络进行的查询,因此由于可能的超时,无法确保每小时有60个条目。
我想计算过去X小时userCount列的小时平均值。
有人知道吗?
备注:如果无法通过sql实现,我想通过PHP解决这个问题

最佳答案

你只需要从时间中提取日期和时间。我会坚持人类的时间:

select date(humanTime) as dd, hour(humanTime) as hh, avg(userCount)
from t
group by date(humanTime), hour(humanTime)
order by dd, hh;

如果您想要最后的“n”小时,请包括:
where humanTime >= date_sub(now(), interval "n" hour)

07-26 01:54
查看更多