3

我正在寻找一个计算平均评论时间(每个月测量)的 SQL 查询。

我能够编写一个查询来测量原始帖子日期时间和评论日期时间之间的平均时间,但这仍然不正确,因为应该在当前评论和前一个评论之间测量时间,因为它们大部分时间都是相关的.


select 
  dateadd(month, datediff(month, 0, Comments.creationdate),0) [Date],
  AVG(CAST(DATEDIFF(hour, Posts.CreationDate, Comments.creationdate ) AS BigInt)) [DelayHours]
  from comments
    INNER JOIN posts ON Comments.PostId = Posts.Id
  GROUP BY
    dateadd(month, datediff(month, 0, Comments.creationdate),0)
  ORDER BY Date
4

1 回答 1

1

我认为这样的事情应该有效。抱歉,我目前无法测试;如果我印刷有误,我深表歉意。

WITH cte1 AS
(
SELECT c.PostId, c.creationdate, 
ROW_NUMBER() OVER (PARTITION BY c.PostId ORDER BY c.creationdate) AS rn
FROM comments c
)
SELECT dateadd(month, datediff(month, 0, a.creationdate),0) [Date],
AVG(diff_hr) AS avg_diff
FROM 
(
  SELECT a1.PostId, a1.creationdate,
  CASE
   WHEN a1.rn = 1 THEN 
    CAST(DATEDIFF(hour,p.creationdate,a1.creationdate) AS BIGINT) 
   ELSE
    CAST(DATEDIFF(hour,a2.creationdate,a1.creationdate) AS BIGINT) 
  END AS diff_hr
  FROM cte1 a1
  INNER JOIN posts p ON (p.Id = a1.PostId)
  LEFT JOIN cte1 a2 ON (a2.PostId = a1.PostId AND a2.rn = a1.rn-1)
)a
GROUP BY dateadd(month, datediff(month, 0, a.creationdate),0)

SQLServer 2012的更新LAG将简化解决方案......我注意到关于版本的评论太晚了。

更新 2错误打印已修复(遗漏FROM子句并p.PostId更改p.Id为匹配表定义)

于 2013-01-19T15:33:15.053 回答