2015-07-21 66 views
1

这是我的表/输出的样子:的Oracle SQL - 两个日期之间的差异为多个ID

ID  ID_2  Status    Timestamp 
------- ----------- ------------------- -------------------- 
4613840 19668170 Submitted   05-06-2015 16:37:00 
4613840 19668330 Submitted   05-06-2015 16:44:00 
4613840 19668409 In Progress   05-06-2015 16:48:00 
4613840 19669674 SupplierPend  05-06-2015 17:43:00 
4613840 19705863 SupplierPend  09-06-2015 15:01:00 
4613840 19735270 In Progress   12-06-2015 11:38:00 
4613840 19735282 Information Pend 12-06-2015 11:38:00 
4613840 19735383 Closed    12-06-2015 11:42:00 

我需要追加一栏包含日期之间的差值(以分钟为单位)结束。

预期输出:

ID  ID_2  Status    Timestamp   Result 
------- ----------- ------------------- ------------------- --------- 
4613840 19668170 Submitted   05-06-2015 16:37:00 0:07:00 
4613840 19668330 Submitted   05-06-2015 16:44:00 0:04:00 
4613840 19668409 In Progress  05-06-2015 16:48:00 0:55:00 
4613840 19669674 SupplierPend  05-06-2015 17:43:00 93:18:00 
4613840 19705863 SupplierPend  09-06-2015 15:01:00 68:37:00 
4613840 19735270 In Progress  12-06-2015 11:38:00 0:00:00 
4613840 19735282 Information Pend 12-06-2015 11:38:00 0:04:00 
4613840 19735383 Closed    12-06-2015 11:42:00 

用于第一行的结果是与ID 19668330和时间戳与ID 19668170时间戳之间的差。

+1

在哪些日期之间?请编辑您的问题并提供您想要的结果。 –

+0

这些定义为Oracle中的日期或时间戳吗? – tbone

回答

2

如果您希望时间在几分钟内(按时间顺序排列),请使用lead()。下面得到的差异在一天的分数:

select t.*, 
     (lead(timestamp) over (partition by id order by timestamp) - timestamp 
     ) as DayFrac 
from table t; 

这将值转换为分钟:

select t.*, 
     (lead(timestamp) over (partition by id order by timestamp) - timestamp 
     ) * 60 * 24 as Minutes 
from table t; 
+0

工作完美!非常棒的队友! –

0

试着这么做:

with x as (
select 1 as id, 'Start' as status, to_timestamp('20150721 07:15:00', 'YYYYMMDD HH24:MI:SS') as ts from dual 
union all 
select 1 as id, 'Processing' as status, to_timestamp('20150721 08:00:00', 'YYYYMMDD HH24:MI:SS') as ts from dual 
union all 
select 1 as id, 'Completed' as status, to_timestamp('20150721 08:05:00', 'YYYYMMDD HH24:MI:SS') as ts from dual 
union all 
select 2 as id, 'Start' as status, to_timestamp('20150721 08:15:00', 'YYYYMMDD HH24:MI:SS') as ts from dual 
union all 
select 2 as id, 'Processing' as status, to_timestamp('20150721 08:30:00', 'YYYYMMDD HH24:MI:SS') as ts from dual 
union all 
select 2 as id, 'Completed' as status, to_timestamp('20150721 08:32:00', 'YYYYMMDD HH24:MI:SS') as ts from dual 
) 
select id, status, ts1, ts2 - ts1 as timespan 
from (
    select id, status, ts as ts1, lead(ts, 1) over (partition by id order by ts asc) ts2 
    from x 
) 

输出:

ID STATUS TS1 TIMESPAN 
1 Start 7/21/2015 7:15:00.000000000 AM +00 00:45:00.000000 
1 Processing 7/21/2015 8:00:00.000000000 AM +00 00:05:00.000000 
1 Completed 7/21/2015 8:05:00.000000000 AM 
2 Start 7/21/2015 8:15:00.000000000 AM +00 00:15:00.000000 
2 Processing 7/21/2015 8:30:00.000000000 AM +00 00:02:00.000000 
2 Completed 7/21/2015 8:32:00.000000000 AM