![](/img/trans.png)
[英]How to get the average of a column that is connected to a datetime column in mysql?
[英]How to get the average interval from a single datetime column?
我的 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
我使用表名作為部門
嘗試這個
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.