SQL:删除具有较早日期的2个或多个记录中的一个(或全部)记录

时间:2017-04-07 08:58:29

标签: sql sql-server

我想实现这样的目标,这在SQL Server 2000中是不可能的。

DELETE 
    TOP 1 
FROM 
    attendance 
WHERE 
    student_id = '201601292' 
ORDER BY 
    attend_date ASC

无意中,在表格中输入了重复记录,我想删除所有重复记录,但最新(或最旧的)重复记录。

请注意,该表格中包含无主键。由于它是SQL Server 2000版,因此'WITH'关键字不可用。此外,'attend_date'列是datetime列。

4 个答案:

答案 0 :(得分:3)

简单的答案,应该适用于任何dbms:

DELETE FROM attendance WHERE student_id = '201601292'
AND attend_date < (select max(attend_date)
                   from attendance WHERE student_id = '201601292')

或者,更一般地说,对所有学生来说:

DELETE FROM attendance a1
WHERE attend_date < (select max(attend_date)
                   from attendance WHERE student_id = a1.student_id)

答案 1 :(得分:1)

也许像

EDIT删除了目标表的别名(语法错误)

DELETE FROM attendance 
WHERE attendance.attendance_date NOT IN
(
SELECT MAX(x.attendance_date) FROM attendance AS x WHERE x.student_id=attendance.student_id
);

答案 2 :(得分:0)

请尝试使用以下代码:

DECLARE @attendance TABLE (student_id VARCHAR(20), attend_date  date);
INSERT INTO @attendance (student_id, attend_date ) VALUES
('201601292','Feb 3 2017'),
('201601292','Feb 4 2017'),
('201601292','Mar 1 2017'),
('201601293','Feb 3 2017'),
('201601293','Feb 4 2017'),
('201601293','Mar 1 2017')


DELETE A FROM @attendance A
INNER JOIN
    (
    SELECT student_id,MAX(attend_date) AS attend_date  FROM @attendance 
    GROUP BY student_id
    ) B 
ON A.student_id <> B.student_id AND A.attend_date <> B.attend_date

SELECT * FROM @attendance

输出

student_id  attend_date
201601292   2017-03-01
201601293   2017-03-01

答案 3 :(得分:0)

您可以使用INNER JOIN包含要删除的不匹配行,如下所示:

DELETE 
FROM  
    attendance a
INNER JOIN (
    SELECT 
        student_id, MAX(attend_date) 
    FROM 
        attendance
    GROUP BY 
        student_id
    ) b
ON 
    a.student_id <> b.student
AND 
    a.attend_date <> b.attend_date 

您可以参考此sql-fiddle进行试用。