我真的很无知如何做到这一点。
说我的表看起来像这样:
MESSAGES
- id
- date_posted
- content
如何获得贴子之间的平均时间? (date_posted)
答案 0 :(得分:2)
SELECT AVG(period)
FROM (
SELECT TIME_TO_SEC(TIMEDIFF(@date_posted, date_posted)) AS period,
@date_posted := date_posted
FROM (
SELECT @date_posted := NULL
) vars,
messages
ORDER BY
date_posted
) q
答案 1 :(得分:1)
试试这个:
SELECT AVG(DATEDIFF(s, M2.Date_Posted, M1.Date_Posted)) as AverageSeconds
FROM Messages M1 INNER JOIN Messages M2 ON M1.Id = M2.Id+1
很抱歉这是MS-SQL解决方案而不是mySQL - 道歉只是意识到这就是你所追求的。这可能对其他人有用。
响应下面的评论 - 在SQL Server 2005或2008中 - 以下是更好的解决方案,因为它不会假设顺序或实际上是整数主键,因为它使用Row_Number生成唯一的顺序键: / p>
SELECT AVG(DATEDIFF(s, M2.Date_Posted, M1.Date_Posted)) as AverageSeconds
FROM (SELECT ROW_NUMBER() OVER(ORDER BY Date_Posted ASC) as Id, Date_Posted FROM
Messages) M1
INNER JOIN (SELECT ROW_NUMBER() OVER(ORDER BY Date_Posted ASC) as Id, Date_Posted
FROM Messages) M2 ON M1.Id = M2.Id+1