Oracle SQL选择匹配查询 [英] Oracle SQL Select Matching Query

查看:83
本文介绍了Oracle SQL选择匹配查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面有这张桌子

uid    rid   time_type    date_time

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

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

Can I use a normal select query to extract the data such that it becomes

uid    rid   time_type    date_time

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

逻辑是1的time_type需要与下一个对应的time_type 2配对才能实现相同的摆脱.能做到吗?

The logic is that time_type of 1 needs to be paired with the next corresponding time_type 2 for the same rid. Can this be done?

推荐答案

您可以尝试以下方法:

-- sample of data from the question
SQL> with t1(uid1, rid, time_type, date_time) as
  2  (
  3    select 'a11',  1, 1, '5/4/2013 00:32:00' from dual union all
  4    select 'a43',  2, 1, '5/4/2013 00:32:01' from dual union all
  5    select 'a68',  2, 2, '5/4/2013 00:32:02'  from dual union all
  6    select 'a98',  2, 1, '5/4/2013 00:32:03'  from dual union all
  7    select 'a45',  2, 1, '5/4/2013 00:32:04'  from dual union all
  8    select 'a94',  1, 2, '5/4/2013 00:32:05'  from dual union all
  9    select 'a35',  2, 2, '5/4/2013 00:32:07'  from dual union all
 10    select 'a33',  2, 2, '5/4/2013 00:32:08'  from dual
 11  ) -- the query
 12  select uid1
 13       , rid
 14       , time_type
 15       , date_time
 16    from (select uid1
 17               , rid
 18               , time_type
 19               , date_time
 20               , row_number() over(partition by rid, time_type order by rid) as rn
 21            from t1
 22          )
 23  order by rid, rn, time_type
 24  /

结果:

UID1        RID  TIME_TYPE DATE_TIME
---- ---------- ---------- -----------------
a11           1          1 5/4/2013 00:32:00
a94           1          2 5/4/2013 00:32:05
a43           2          1 5/4/2013 00:32:01
a68           2          2 5/4/2013 00:32:02
a98           2          1 5/4/2013 00:32:03
a35           2          2 5/4/2013 00:32:07
a45           2          1 5/4/2013 00:32:04
a33           2          2 5/4/2013 00:32:08

8 rows selected

SQLFiddle演示

这篇关于Oracle SQL选择匹配查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆