我有一张这样的表:
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。
由于
答案 0 :(得分: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)))
答案 1 :(得分: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
答案 2 :(得分: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))