0

我有一个包含以下 3 列的表

Recid (primary key), different_recid(foreign key), and details

我想为 10 编写一个查询,different_recids以删除different_recids除最近的行之外的所有行。

任何人都有建议。

4

1 回答 1

0
DECLARE @MyTable TABLE
(
    RecID           INT IDENTITY(1,1) PRIMARY KEY,
    Different_RecID INT,
    Create_Date     DATETIME
);

INSERT  @MyTable (Different_Recid, Create_Date)
SELECT  1, '20130101' UNION ALL 
SELECT  1, '20130102' UNION ALL 
SELECT  1, '20130103' UNION ALL 

SELECT  2, '20130211' UNION ALL 
SELECT  2, '20130212' UNION ALL 

SELECT  3, '20130102' UNION ALL 
SELECT  3, '20130103';

DECLARE @RowsToDelete TABLE(ID INT PRIMARY KEY);
INSERT  @RowsToDelete VALUES (1);
INSERT  @RowsToDelete VALUES (2);

DELETE  [Target]
-- OUTPUT   deleted.* -- <-- Uncomment this line to see deleted rows
FROM
(
    SELECT  *
    FROM
    (
        SELECT  ROW_NUMBER() OVER(PARTITION BY x.Different_RecID ORDER BY x.Create_Date DESC) RowNum, x.*
        FROM    @MyTable x
        WHERE   EXISTS 
        (   
            SELECT  *
            FROM    @RowsToDelete d 
            WHERE   x.Different_RecID = d.ID
        )
    ) src
    WHERE src.RowNum > 1
) AS [Target];

结果:

SELECT * FROM @MyTable;
/*
RecID Different_RecID Create_Date
----- --------------- -----------
3     1               2013-01-03
5     2               2013-02-12
6     3               2013-01-02
7     3               2013-01-03
*/
于 2013-10-02T19:50:53.920 回答