How to improve oracle row_number in query

五迷三道 提交于 2019-12-12 05:29:24

问题


Table_A
-------------------
A_id          
-------------------
1     

Table_B
-------------------
B_id   |     A_id
-------------------
1            1
2            1
3            1

Table_C
-----------------------------
B_id  |   Process_date
-----------------------------
1         20130101 12:20:01
2         20130101 12:10:01
3         20130101 13:00:01

How to retrieve the maximum process_date from Table_C with references of Table_A.A_id based on Table_C timing window. If I want to retrieve Table_C.b_id and max(process_date) in timing window 20130101 12:09:00 to 12:21:00 then it should return id as 1 and process_date as 12:20:01

Below query Is i am using:

select b_id, 
       process_date
  from (select c1.b_id,
               c1.process_date,
               row_number() over(partition by a.a_id 
                                 order by c1.process_date desc) rn
          from table_a a
               inner join 
               table_b b
                 on a.a_id = b.a_id
               inner join 
               table_c c1
                 on b.b_id = c1.b_id
       ) 
 where rn = 1;

回答1:


If I follow, you want the maximum process date and corresponding b_id for a given a_id where the process date is within a set date range. Here is a solution not requiring any analytic functions or row number. I'm using a with clause and dual just to replicate your sample tables. You can remove that if you have table_a, table_b, table_c.

with table_a as 
(
 select 1 a_id from dual
),
table_b as 
(
 select 1 b_id, 1 a_id from dual union all
 select 2 b_id, 1 a_id from dual union all
 select 3 b_id, 1 a_id from dual
), table_c as
(
 select 1 b_id, to_date('20130101 12:20:01', 'yyyymmdd hh24:mi:ss') process_date from dual union all
 select 2 b_id, to_date('20130101 12:10:01', 'yyyymmdd hh24:mi:ss') process_date from dual union all
 select 3 b_id, to_date('20130101 13:00:01', 'yyyymmdd hh24:mi:ss') process_date from dual
) 
select table_c.b_id, 
       table_c.process_date
  from table_b,
       table_c
 where table_b.b_id = table_c.b_id
   and table_b.a_id = 1
   and table_c.process_date = (select max(process_date)
                                 from table_b b2,
                                      table_c c2
                                where table_b.a_id = b2.a_id
                                  and b2.b_id = c2.b_id
                                  and c2.process_date between to_date('20130101 12:09:00', 'yyyymmdd hh24:mi:ss')  and 
                                                              to_date('20130101 12:21:00', 'yyyymmdd hh24:mi:ss')
                              )

returns:

----------------------------
b_id  |  process_date
----------------------------
1       1/1/2013 12:20:01


来源:https://stackoverflow.com/questions/15259989/how-to-improve-oracle-row-number-in-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!