簡體   English   中英

如何從充滿重復項的表中選擇最新記錄

[英]How do I select the most recent records from a table full of duplicates

我有下表,需要查詢才能產生預期的結果。

**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的記錄。

進行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"

您還可以使用下面的查詢獲取所需的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM