简体   繁体   English

仅基于SQL中的条件删除表中的重复项

[英]Deleting duplicates in a table based on a criteria only in SQL

Let's say I have a table with columns: 假设我有一个包含列的表格:

CustomerNumber
Lastname
Firstname
PurchaseDate

...and other columns that do not change anything in the question if they're not shown here. ......以及其他不改变问题内容的列,如果它们没有在这里显示的话。

In this table I could have many rows for the same customer with different purchase dates (I know, poorly designed... I'm only trying to fix an issue for reporting, not really trying to fix the root of the problem). 在这个表中,我可以为同一个客户提供许多行,具有不同的购买日期(我知道,设计不佳......我只是试图解决报告问题,而不是真正尝试解决问题的根源)。

How, in SQL, can I keep one record per customer with the latest date, and delete the rest? 在SQL中,如何为每个客户保留一条记录,并删除其余的日期? A group by doesn't seem to be working for my case 一个group by似乎没有为我的案子工作

;with a as
(
select row_number() over (partition by CustomerNumber, Lastname, Firstname order by PurchaseDate desc) rn
from <table>
)
delete from a where rn > 1

This worked for me (on DB2): 这对我有用(在DB2上):

 DELETE FROM my_table 
 WHERE (CustomerNumber, Lastname, Firstname, PurchaseDate) 
 NOT IN ( 
       SELECT CustomerNumber, Lastname, Firstname, MAX(PurchaseDate) 
       FROM my_table 
       GROUP BY CustomerNumber, Lastname, FirstName 
 )
SELECT CustomerNumber, Lastname, Firstname, MAX(PurchaseDate) LatestPurchaseDate
FROM Table
GROUP BY CustomerNumber, Lastname, Firstname

The MAX will select the highest (latest) date and show that date for each unique combination of the GROUP BY columns. MAX将选择最高(最新)日期,并显示GROUP BY列的每个唯一组合的日期。

EDIT: I misunderstood that you wanted to delete records for all but the latest purchase date. 编辑:我误解你想删除除最近购买日期以外的所有记录。

WITH Keep AS
(
    SELECT CustomerNumber, Lastname, Firstname, MAX(PurchaseDate) LatestPurchaseDate
    FROM Table
    GROUP BY CustomerNumber, Lastname, Firstname
)
DELETE FROM Table
WHERE NOT EXISTS
(
    SELECT *
    FROM Keep
    WHERE Table.CustomerNumber = Keep.CustomerNumber
    AND Table.Lastname = Keep.Lastname
    AND Table.Firstname = Keep.Firstname
    AND Table.PurchaseDate = Keep.LastPurchaseDate
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM