-2
URN New_Value       Old_Value   Insert_Timestamp
1   A               B           01:00
2   C               A           02:00
3   A               D           03:00
4   B               E           04:00
5   G               B           05:00
6   I               J           06:00

我只需要提取 URN 1 到 6。因为所有其他 URN 都包含其中一个new_valueold_value已在其时间戳之前使用的时间戳。

4

4 回答 4

2
select t1.*
from MyTable t1
left outer join MyTable t2 on (t1.New_Value = t2.New_Value or t1.New_Value = t2.old_Value) 
    and t2.Insert_Timestamp < t1.Insert_Timestamp
left outer join MyTable t3 on (t1.Old_Value = t3.Old_Value or t1.Old_Value = t3.New_Value) 
    and t3.Insert_Timestamp < t1.Insert_Timestamp 
where t2.URN is null and t3.URN is null

SQL 小提琴示例

于 2012-09-28T16:51:30.267 回答
2

尝试使用not exists子句代码:

select * from tab t
where not exists
(
  select * from tab t2
  where t2.Insert_Timestamp<t.Insert_Timestamp
  and (t.New_Value=t2.New_Value or t.Old_Value=t2.Old_Value or
       t.Old_Value=t2.New_Value or t.New_Value=t2.Old_Value )
)

SQL 小提琴演示

于 2012-09-28T17:17:37.080 回答
1

这种模式和要求的性能可能会很差,但是

SELECT *
FROM   YourTable T1
WHERE  NOT EXISTS (SELECT *
                   FROM   YourTable T2
                   WHERE  T2.Insert_Timestamp < T1.Insert_Timestamp
                          AND ( T2.New_Value IN ( T1.New_Value, T1.Old_Value )
                                 OR T2.Old_Value IN ( T1.New_Value, T1.Old_Value ) )) 
于 2012-09-28T16:52:56.987 回答
0

由于我不知道您使用的是什么数据库服务器,或者您的最终目标是什么,我可以想象一个通用的 SQL 语句可能会起作用。你可以使用这样的东西:

SELECT
 URN,
 New_Value,
 Old_Value,
 Insert_Timestamp
FROM
 table t
WHERE
 t.URN BETWEEN 1 AND 6
于 2012-09-28T16:50:04.717 回答