下面需要Oracle SQL查询帮助

时间:2013-08-24 09:38:42

标签: sql oracle

我有如下表:

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)

3 个答案:

答案 0 :(得分: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';

如果有多个行具有相同的ref_num且max()

type = 'Y'只是一种预防措施

答案 1 :(得分: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;

答案 2 :(得分: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;