0

我有如下表:

ID  ref num  type   time stamp
------------------------------
1   456      X      Time 1
2   456      Y      updated Timestamp
3   678      X      Time 3
4   678      Y      updated timestamp

我需要帮助来构建一个查询,该查询将为我提供如下结果:

ref num    Type Time difference
------------------------------------
456         X   (Timestamp diff between Type X and Type Y for a ref num)
678         Y   (Timestamp diff between Type X and Type Y for a ref num)
4

3 回答 3

0

一种解决方案是使用共同相关的子查询来获取相应的 time_stamp 值:

select t1.id, 
       t1.ref_num,
       t1.type, 
       t1.time_stamp - (select max(t2.time_stamp) from the_table t2 where t2.ref_num = t1.ref_num and t2.type = 'Y') as diff
from the_table t1
where t1.type = 'X';

max()只是一种预防措施,以防多行具有相同的 ref_num 和type = 'Y'

于 2013-08-24T11:10:58.173 回答
0

您可以使用条件聚合来做到这一点:

select t.refnum,
       (max(case when type = 'X' then timestamp end) -
        max(case when type = 'Y' then timestamp end)
       ) as TypeTimeStampDiff
from t
group by t.refnum;
于 2013-08-24T11:26:19.090 回答
0

有趣,但根据提供的信息,我所了解的只是

select t.Ref_Num,
   (case
      when Rownum mod 2 = 0 then
       'Y'
      else
       'X'
    end) type,
   max(case when type = 'Y' then t.time_stamp end) - 
       min(case when type = 'X' then t.time_stamp end)) as Typetimestampdiff

来自 Table_Name t 组的 t.Refnum;

于 2013-08-24T14:12:28.170 回答