我的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分钟评论一次。
我不知道如何为此编写查询。
答案 0 :(得分:2)
您可以通过将总跨度除以评论数减去一来获得评论之间的平均间距:
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;
答案 1 :(得分:0)
请尝试这个
SELECT user_id,department, FROM_UNIXTIME(AVG(UNIX_TIMESTAMP(comment_time))) as average_time
FROM dept
GROUP by user_id
我使用表名作为部门
答案 2 :(得分:0)
尝试
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