在mysql数据库中查找行和时间戳之间的交叉点

时间:2013-02-27 12:19:57

标签: mysql sql sqlite postgresql timestamp

我有一张表,其中列出了某些对象的事件。

有两个事件:“移动”和“加载”。它们可以开始和结束,并且这些事件在发生时会带有时间戳。

现在我要计算以下三个数字:

  • 时间的总和,当运动发生时(小提琴中的值:700)
  • 加载发生的时间总和(小提琴中的值:630)
  • 时间的总和,当移动和载荷发生时(小提琴中的值:611)

我在这里为这个问题创建了一个sqlfiddle:

http://sqlfiddle.com/#!2/be512

3 个答案:

答案 0 :(得分:2)

试试这个

对于加载答案将是630而不是690

对于第一和第二种情况

SELect max(timestamp) - min(timestamp), LEFT(event, LOCATE(' ', event)) 
FROM table1 
group by id, LEFT(event, LOCATE(' ', event));

第三种情况

SELect max(timestamp) - min(timestamp), id
FROM table1 
group by id;

FIDDLE

答案 1 :(得分:1)

前两列计算相应end / start事件之间的差异。 (求和是可交换的,因此我们不需要实际匹配相应的事件。)

第三列搜索前一movement start事件为load事件的load start事件,以及movement end以下事件load事件事件是load end事件。

SELECT (SELECT SUM(timestamp)
        FROM Table1
        WHERE event = 'movement end') -
       (SELECT SUM(timestamp)
        FROM Table1
        WHERE event = 'movement start') AS all_movement,

       (SELECT SUM(timestamp)
        FROM Table1
        WHERE event = 'load end') -
       (SELECT SUM(timestamp)
        FROM Table1
        WHERE event = 'load start') AS all_load,

       (SELECT SUM(timestamp)
        FROM Table1 a
        WHERE event = 'movement end' AND
              (SELECT event
               FROM Table1 b
               WHERE timestamp = (SELECT min(timestamp)
                                  FROM Table1 c
                                  WHERE c.timestamp >= a.timestamp
                                    AND c.event LIKE 'load %')
              ) = 'load end') -
       (SELECT SUM(timestamp)
        FROM Table1 a
        WHERE event = 'movement start' AND
              (SELECT event
               FROM Table1 b
               WHERE timestamp = (SELECT max(timestamp)
                                  FROM Table1 c
                                  WHERE c.timestamp <= a.timestamp
                                    AND c.event LIKE 'load %')
              ) = 'load start') AS load_movement;

答案 2 :(得分:1)

这是获取开始和结束之间时间的查询:

select sum(a.timestamp-b.timestamp) from Table1 a join Table1 b on a.rowid-b.rowid=1 and a.rowid%2=0 and a.event='movement end';

类似,在结束和开始之间:

select sum(a.timestamp-b.timestamp) from Table1 a join Table1 b on a.rowid-b.rowid=1 and a.rowid%2=1 and a.event='movement start';