我有一个表格,其中包含结束时间,活动ID,记录编号。我需要做的是从记录1的时间减去记录2的时间,从记录3的时间减去记录4的时间。
table data
started activity Id record Id
11/14/2013 11:06:29 PM 1257 1
11/15/2013 2:09:57 PM 1291 2
11/18/2013 4:26:34 AM 1257 3
11/18/2013 4:48:53 PM 1291 4
11/19/2013 2:54:52 AM 1257 5
11/19/2013 3:42:00 PM 1291 6
11/21/2013 2:24:38 AM 1257 7
11/21/2013 2:08:06 PM 1291 8
我不知道怎么做,有人可以帮忙。
答案 0 :(得分:0)
SQL中的表达式一次引用一行。
因此,当您希望表达式在SQL中引用两行时,您需要一个自连接来将两行转换为一行:
SELECT TO_SECONDS(t2.started) - TO_SECONDS(t1.started) AS difference_in_seconds
FROM `table data` AS t1
JOIN `table data` AS t2
ON t2.record_id = t1.record_id + 1
答案 1 :(得分:0)
假设您的ID是按顺序分配的,并定义“记录1”和“记录2”的含义,您可以通过聚合执行此操作:
select max(case when id % 2 = 1 then id end) as id1,
max(case when id % 2 = 0 then id end) as id2,
to_seconds(max(t2.started)) - to_second(min(t2.started)) as diff
from data
group by floor(id - 1)/2;
这假设时间是按顺序分配的,因此差异从不为负。如果是这种情况,请改用case
:
select max(case when id % 2 = 1 then id end) as id1,
max(case when id % 2 = 0 then id end) as id2,
(to_seconds(max(case when id % 2 = 0 then started end)) -
to_seconds(max(case when id % 2 = 1 then started end))
) as diff
from data
group by floor(id - 1)/2;