我有一些数据(从广义上来说,包括以下字段:
Person TaskID Start_time End_time
Alpha 1 'Wed, 18 Oct 2017 10:10:03 GMT' 'Wed. 18 Oct 2017 10:10:36 GMT'
Alpha 2 'Wed, 18 Oct 2017 10:11:16 GMT' 'Wed, 18 Oct 2017 10:11:28 GMT'
Beta 1 'Wed, 18 Oct 2017 10:12:03 GMT' 'Wed, 18 Oct 2017 10:12:49 GMT'
Alpha 3 'Wed, 18 Oct 2017 10:12:03 GMT' 'Wed, 18 Oct 2017 10:13:13 GMT'
Gamma 1 'Fri, 27 Oct 2017 22:57:12 GMT' 'Sat, 28 Oct 2017 02:00:54 GMT'
Beta 2 'Wed, 18 Oct 2017 10:13:40 GMT' 'Wed, 18 Oct 2017 10:14:03 GMT'
对于此数据,我所需的输出如下:
Person TaskID Time_between_attempts
Alpha 1 NULL ['Wed, 18 Oct 2017 10:10:03 GMT' - NULL]
Alpha 2 0:00:40 ['Wed, 18 Oct 2017 10:11:16 GMT' -'Wed, 18 Oct 2017 10:10:36 GMT']
Beta 1 NULL ['Wed, 18 Oct 2017 10:12:03 GMT' - NULL]
Alpha 3 0:00:35 ['Wed, 18 Oct 2017 10:12:03 GMT' -'Wed, 18 Oct 2017 10:11:28 GMT']
Gamma 1 NULL ['Fri, 27 Oct 2017 22:57:12 GMT' - NULL]
Beta 2 0:00:51 ['Wed, 18 Oct 2017 10:13:40 GMT' -'Wed, 18 Oct 2017 10:12:49 GMT']
我的要求如下:
a。对于给定的人(Alpha,Beta或Gamma),变量'time_between_attempts'的首次出现为零/ NULL-在示例中,我将其显示为NULL。
b。第二次(及以后),同一个人出现的时间将为非NULL或非零的“ time_between_attempts”。该变量是通过计算上一个任务的结束时间和下一个任务的开始时间之间的差来计算的。
我在这方面有两个问题:
如何分割Start_time和End_time列,以将日/月信息与YYYY HH:MM:SS信息分开?
如何编写可以帮助我实现所需输出的SQL脚本?任何建议对此将不胜感激。
使用self Join()方法。
SELECT a.person,
a.taskid,
a.start_time,
b.end_time
FROM test a
LEFT JOIN test b
ON a.person = b.person
AND a.taskid = b.taskid + 1
ORDER BY 1, 2;
这将回答问题的原始版本。
您可以使用lag()
和timestampdiff()
进行计算。假设您的值是真实的日期/时间或时间戳,那么您可以轻松地以秒为单位计算该值:
select t.*,
timestampdiff(start_time,
lag(end_time) over (partition by person_id order by start_time,
seconds
)
from t;
如果值存储为字符串,请修复数据!同时,您可以在功能中使用str_to_date()
。
将其作为时间值:
select t.*,
(time(0) +
interval timestampdiff(start_time,
lag(end_time) over (partition by person_id order by start_time,
seconds
) second
)
from t;