6

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

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

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

  • 发生移动的时间总和(小提琴中的值:700)
  • 负载发生时的时间总和(小提琴中的值:630)
  • 发生移动和负载的时间总和(小提琴中的值:611)

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

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

4

3 回答 3

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;

小提琴

于 2013-02-27T13:09:10.740 回答
1

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

第三列搜索movement start前一个load事件是事件的load start事件,以及movement endload一个事件是事件的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;
于 2013-02-27T13:11:26.867 回答
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';
于 2013-02-27T13:15:14.210 回答