我的mysql数据库中有下表。
user_id| department | comment_time
-----------------------------------------
ahnaf | OM1 | 2018-02-01 10:00:00
muttaki| OM2 | 2018-02-01 11:00:00
sunny | OM3 | 2018-02-01 12:00:00
ahnaf | OM1 | 2018-02-01 21:00:00
john | OM2 | 2018-02-01 23:00:00
从这张表中我想知道某个部门的人经常发表评论的频率。我正在寻找一个答案:OM1的一个人平均每5分钟评论一次。
我不知道如何为此编写查询。
您可以通过获取总跨度并除以小于注释数量的1来获得注释之间的平均间距:
select department,
( ( to_seconds(max(comment_time)) - to_seconds(min(comment_time))
) / nullif(count(*) - 1, 0)
) / 60 as avg_comment_in_minutes
from t
group by department;
如果您知道评论是最新的,并且您想要处理自最近评论以来的范围,那么您可以:
select department,
( ( to_seconds(now()) - to_seconds(min(comment_time))
) / count(*)
) / 60 as avg_comment_in_minutes
from t
group by department;
请试试这个
SELECT user_id,department, FROM_UNIXTIME(AVG(UNIX_TIMESTAMP(comment_time))) as average_time
FROM dept
GROUP by user_id
我正在使用表名作为dept
试试这个
select department,
avg(diff_comment_time) FROM
(select department,
LAG(comment_time) OVER ( PARTITION BY department ORDER BY comment_time DESC) - comment_time as diff_comment_time
from test) test2
group by department