Oracle to retrieve maximum record

南笙酒味 提交于 2019-12-13 20:08:18

问题


Table_A

A_id          
1     



Tale_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 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


回答1:


You can use a subquery that gets the max(process_date):

select c1.b_id,
  c2.MaxDate
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
inner join
(
  select max(process_date) MaxDate
  from table_c
) c2
  on c1.process_date = c2.maxdate;

See SQL Fiddle with Demo

Or you can use row_number():

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

See SQL Fiddle with Demo




回答2:


This query should get you the max process_date for each B_id with a reference in Table_A:

SELECT c.B_id, MAX(Process_date)
FROM Table_C c
INNER JOIN Table_B b 
    ON b.B_id = c.B_id
INNER JOIN Table_A a
    ON a.A_ID = b.A_id
GROUP BY c.B_id

Just remove the c.B_id from the select and the GROUP BY if you want the max process_date of all B_id's with a reference to Table_A.

SQL Fiddle



来源:https://stackoverflow.com/questions/15234479/oracle-to-retrieve-maximum-record

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