-1

我在下面有这张表

uid    rid   time_type    date_time

a11    1     2            5/4/2013 00:32:00 (row1)
a43    1     1            5/4/2013 00:32:01 (row2)
a68    1     1            5/4/2013 00:32:02 (row3)
a98    1     2            5/4/2013 00:32:03 (row4)
a45    1     2            5/4/2013 00:32:04 (row5)
a94    1     1            5/4/2013 00:32:05 (row6)
a35    1     2            5/4/2013 00:32:07 (row7)
a33    1     2            5/4/2013 00:32:08 (row8)

我可以使用普通的选择查询来提取数据,使其变为

uid    rid   time_type    date_time

a43    1     1            5/4/2013 00:32:01 (row2)
a98    1     2            5/4/2013 00:32:03 (row4)
a94    1     1            5/4/2013 00:32:05 (row6)
a35    1     2            5/4/2013 00:32:07 (row7)

date_time 字段按升序排列。逻辑是 time_type '1' 需要与下一个 time_type '2' 配对。如果 time_type '1' 或 '2' 出现在按 date_time 排序的 2 个或更多的一组中,我将取较早的一个并忽略其余的。

这可以做到吗?

4

1 回答 1

0

Try this query:

with src as (
  select tst.*,  
         case when time_type <> lag( time_type) over ( partition by rid order by date_time, time_type ) 
            then 1 else 0
         end take_me
  from tst
) 
select * from src where take_me = 1
order by rid, date_time;

Here is an SQL Fiddle demo

于 2013-07-24T00:09:30.340 回答