简体   繁体   English

计算每月表中的平均小时数

[英]Calculate the average number of hours in table per month

I have a table named "loginhistory", and I need to calculate the most active hour of the month. 我有一个名为“ loginhistory”的表,我需要计算一个月中最活跃的小时。 How can i do it? 我该怎么做?

My table structure is: id, userId, date (datetime), ip. 我的表结构是:id,userId,日期(datetime),ip。

I tried to do it in PHP but I did not succeed there either. 我试图用PHP做到这一点,但我也没有成功。 I prefer the calculation to be done only in MySql. 我希望仅在MySql中进行计算。

I expect the output to be just the number of the most active hour. 我希望输出只是最活跃的小时数。

It does not matter checking average number if needed to pick active hour. 如果需要选择活动时间,则检查平均数无关紧要。

Cause average = count / days and since days is the same for whole calculation (let's say 30 ) the greatest count will be active hour in list. 原因average = count / days ,由于整个计算的days相同(假设为30 ),因此最大的count将是列表中的活动小时count

Just select by date range and group by hour and pick 1st one from descending sort: 只需按日期范围选择并按小时分组,然后从降序中选择第一个即可:

SELECT 
  HOUR(date) AS hour,
  COUNT(id) AS logins,
  ( COUNT(id) / DAY(LAST_DAY('2019-01-01')) ) AS logins_avg
FROM loginhistory
WHERE 
  date >= '2019-01-01 00:00:00' AND date < '2019-02-01 00:00:00'
GROUP BY HOUR(date)
ORDER BY logins DESC LIMIT 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM