0

我在尝试着

  1. 收集两个不同type的对象(Published并且InReviewing来自同一个模型Events
  2. Published找到和之间的中间时间Created
  3. 按日期分组..

这样我就可以返回一个带有日期的数组,以及任何类型之间的中等时间差,InReviewing并且每天Published共享一个。target_id我认为 SQL 会返回秒数?

例子 :

[[Mon, 03 Dec 2012, 110000], [Thu, 13 Dec 2012, 2200000]]

我的原始 SQL 语法缺乏一些结论。这是我到目前为止所拥有的:

    SELECT target_id, DATE(created_at), COUNT(*)
    FROM (   SELECT target_id, DATE(created_at)
          FROM events
          WHERE created_at > '#{@start_time}'
          AND events.type = 'InReviewing'
          UNION ALL
          SELECT target_id, DATE(created_at)
          FROM events
          WHERE created_at > '#{@start_time}'
          AND events.type = 'Published'   
      ) tmp
    GROUP BY DATE(created_at)

不要介意#{@start_time}`,这是使用本机代码在这里实现时间,它可以正常工作..

谢谢!

4

1 回答 1

1

我不认为我理解您的问题,但我仍然决定试一试(另外,由于我此时无法访问 MySql,因此此示例来自 MS SQL):

    SELECT x.target_id, x.created_at AS InReviewingCreated, y.created_at AS PublishedCreated, DATEDIFF(SECOND, x.created_at, y.created_at) AS DiffSeconds 
FROM 
    (SELECT *
        FROM Events a 
        WHERE a.created_at > '#{@start_time}'
            AND a.type = 'InReviewing') x INNER JOIN

    (SELECT *
        FROM Events a 
        WHERE a.created_at > '#{@start_time}'
            AND a.type = 'Published') y ON x.target_id = y.target_id
ORDER BY x.created_at

这将为您提供每个目标是 InReview 和 Published 的时间戳以及它们之间的秒数。我对你想要什么有点困惑......这是我“认为”你想要的:

SELECT DATEPART(DAYOFYEAR, x.created_at), AVG(DATEDIFF(SECOND, x.created_at, y.created_at))
FROM 
    (SELECT *
        FROM Events a 
        WHERE a.created_at > '#{@start_time}'
            AND a.type = 'InReviewing') x INNER JOIN

    (SELECT *
        FROM Events a 
        WHERE a.created_at > '#{@start_time}'
            AND a.type = 'Published') y ON x.target_id = y.target_id
GROUP BY DATEPART(DAYOFYEAR, x.created_at)
ORDER BY DATEPART(DAYOFYEAR, x.created_at)

免责声明:由于我没有您的表模式,因此我的测试并不完全有效。如果您要共享示例设置和所需的输出,那么我可以提供更好的查询。

希望这可以帮助。

于 2012-12-13T21:57:53.703 回答