比较行的SQL查询

比较行的SQL查询,sql,compare,Sql,Compare,我有一张这样的桌子: Sequence ID Date other fields 1 23 2012-01-01 2 23 2012-02-03 3 23 2012-02-02 4 45 2012-01-01 5 45 2012-01-02 6

我有一张这样的桌子:

    Sequence    ID      Date          other fields

    1           23      2012-01-01
    2           23      2012-02-03
    3           23      2012-02-02
    4           45      2012-01-01
    5           45      2012-01-02
    6           52      2012-01-01
    7           52      2012-03-01
    ..          ...
我需要一个查询,该查询返回具有反转日期的行。它们是具有较旧日期的较高序列

在示例abow中,它应该返回带有序列2和3的rowq。对于id 23,Seq 2的日期比序列号3的日期晚

谢谢

试试这个:

select Sequence,ID,Date 
from   
   ( select *,
     ROW_NUMBER() over (partition by ID order by date) as row_num_date,
     ROW_NUMBER() over (partition by ID order by Sequence) as row_num_seq
     from your_table )a
where row_num_date!=row_num_seq

我已经更新了我的答案。。请检查一下
select * from 
   (select T1.Sequence as S1, T2.Sequence as S2, T1.ID 
    from T as T1, T as T2
    where T1.Sequence < T2.Sequence 
      and T1.Date > T2.Date 
      and T1.ID = T2.ID) Subq
   inner join T on (T.ID = Subq.ID 
               and (T.Sequence = Subq.S1 or T.Sequence = Subq.S2))
select t1.*
from <table> t1
  join <table> t2 
    on  t1.Id=t2.Id
    and (((t1.Sequence>t2.Sequence) and (t1.Date<t2.Date)) or
         ((t1.Sequence<t2.Sequence) and (t1.Date>t2.Date)))