从自己加入中删除

时间:2015-01-27 01:05:06

标签: sql sql-server self-join sql-delete

我正在尝试删除旧日期的重复记录。我刚刚上传了一些日期较晚的副本,只想保留它们。

以下是我的代码

DELETE FROM 
    Config 
WHERE
(
SELECT 
    * 
FROM 
    Config one
INNER JOIN 
    Config two
ON 
    one.name = two.name 
    and 
    one.product = two.product
WHERE 
    (one.name LIKE '4%' OR one.Name LIKE '7%' OR one.Name LIKE '9%') 
    AND 
    (one.date < two.date)
)

我最难得到这个。

编辑:添加表架构

ConfigID GUID UNIQUE IDENTIFIER
name     varchar(100),
Product  varchar(50),
Amount   smallint,
Date     datetime

2 个答案:

答案 0 :(得分:2)

试试这个:

;WITH CTE AS(
    SELECT 
        *, Rn = ROW_NUMBER() OVER(PARTITION BY Product, Name ORDER BY [Date] DESC)
    FROM Config
    WHERE
        name  LIKE '4%'
        OR name  LIKE '7%'
        OR name  LIKE '9%'
)
DELETE FROM CTE WHERE Rn > 1

答案 1 :(得分:1)

我认为应该这样做:

delete one
FROM 
    Config one
    INNER JOIN 
        Config two
    ON 
        one.name = two.name 
        and one.product = two.product
    WHERE 
        (one.name LIKE '4%' OR one.Name LIKE '7%' OR one.Name LIKE '9%') 
        AND (one.date < two.date)