2

我有一张这样的桌子:

    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 更新。

谢谢

4

3 回答 3

3
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)))

和它的小提琴http://sqlfiddle.com/#!3/beaf8/2/0

于 2012-08-30T07:24:40.530 回答
1

尝试这个:

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


SQL 小提琴演示

于 2012-08-30T07:09:35.707 回答
1
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))
于 2012-08-30T07:11:09.303 回答