3

假设我有一个包含列的表:

CustomerNumber
Lastname
Firstname
PurchaseDate

...以及其他列如果未在此处显示,则不会更改问题中的任何内容。

在此表中,我可以为具有不同购买日期的同一客户提供许多行(我知道,设计不佳......我只是试图解决报告问题,而不是真正试图解决问题的根源)。

如何在 SQL 中为每个客户保留一条记录的最新日期,然后删除其余记录?Agroup by似乎不适用于我的情况

4

3 回答 3

7
;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
于 2012-09-20T15:30:45.960 回答
3

这对我有用(在 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 
 )
于 2012-09-20T15:33:08.643 回答
1
SELECT CustomerNumber, Lastname, Firstname, MAX(PurchaseDate) LatestPurchaseDate
FROM Table
GROUP BY CustomerNumber, Lastname, Firstname

MAX 将选择最高(最新)日期,并为 GROUP BY 列的每个唯一组合显示该日期。

编辑:我误解了您想删除除最新购买日期之外的所有记录。

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
)
于 2012-09-20T15:18:55.767 回答