如何从完整重复的表中选择最新记录

时间:2015-11-05 10:53:26

标签: sql database oracle

我已经得到了下表,需要一个查询来产生预期的结果。

**Table**
  Address Num  My_Date
 Address1 7777 03/NOV/15
 Address2 2222 02/NOV/15
 Address2 3333 02/NOV/15
 Address2 2222 05/NOV/15
 Address2 3333 05/NOV/15
 Address3 8888 01/NOV/15
 Address4 9999 04/NOV/15

预期结果

Address  Num  My_Date
Address1 7777 03/NOV/15
Address2 2222 05/NOV/15
Address2 3333 05/NOV/15
Address3 8888 01/NOV/15
Address4 9999 04/NOV/15

正如您所看到的,我需要恢复所有记录,如果有重复的 Num 只带来最近 My_Date 的记录。

2 个答案:

答案 0 :(得分:4)

要么GROUP BY

select address, num, max(date)
from tablename
group by address, num

NOT EXISTS

select *
from tablename t1
where not exists (select 1 from tablename t2
                  where t2.address = t1.address
                    and t2.num = t1.num
                    and t2.date > t1.date)

在ANSI SQL中,date是一个保留字,因此您可能需要将其双引号作为分隔标识符,即"date"

答案 1 :(得分:2)

您还可以使用以下查询来获取所需的o / p

select "Address","Num","Date"
from
(
select "Address","Num","Date",rank() over(partition by "Address" order by "Date" desc) r_no from table_name
)
where r_no=1