sql - 按顺序插入测试记录

时间:2011-08-22 00:10:33

标签: sql database oracle

我有一个带有skey列的表(由序列号生成)和一个时间戳列。

我需要编写一个查询,该查询将查找具有更高skey但旧时间戳比先前记录更旧的记录,因为它将指示问题。

也就是说:

select * from table
where timestamp < (select max(timestamp) from table where skey less than currrecord)
order by skey desc;

2 个答案:

答案 0 :(得分:1)

使用self join,即使用您提到的条件(SKey和TimeStamp)将表连接到自身

Select T1.Skey HigherSkey, T2.SKey LowerSkey, T1.Timestamp LowerTimestamp, T2.Timestamp HigherTimestamp
From MyTable T1
Inner Join MyTable T2
    On T1.Timestamp < T2.Timestamp
    And T1.Skey > T2.Skey

答案 1 :(得分:0)

如果你的序列完整(意味着它没有洞),这样的事情应该有效:

select t2.* from table t1
inner join table t2 on t2.skey = t1.skey + 1
where t2.timestamp < t1.timestamp
order by t2.skey desc;

如果没有,你可以使用这样的东西来获取ID:

select t2.skey from table t1, table t2
where t1.skey < t2.skey and t2.timestamp < t1.timestamp
group by t2.skey