我有一张表,其中列出了某些对象的事件。
有两个事件:“移动”和“加载”。它们可以开始和结束,并且这些事件在发生时会带有时间戳。
现在我要计算以下三个数字:
我在这里为这个问题创建了一个sqlfiddle:
答案 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;
答案 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';