SQL查询以识别并删除除最新记录以外的所有记录
我有以下查询,它根据employee_id字段标识重复记录SQL查询以识别并删除除最新记录以外的所有记录,sql,duplicates,duplicate-removal,Sql,Duplicates,Duplicate Removal,我有以下查询,它根据employee_id字段标识重复记录 SELECT ROW_NUMBER() OVER(PARTITION BY c1.employee_id ORDER BY c1.lastlogon ASC ) AS Row ,[DN] ,[first_name] ,[last_name] ,[init] ,[email] ,[title] ,[display_name] ,[department] ,[phone
SELECT ROW_NUMBER() OVER(PARTITION BY c1.employee_id ORDER BY c1.lastlogon ASC ) AS Row
,[DN]
,[first_name]
,[last_name]
,[init]
,[email]
,[title]
,[display_name]
,[department]
,[phone_num]
,[mob_num]
,[fax_num]
,[pager_num]
,[logon]
,[post_code]
,[www]
,[objectSID]
,[disabled]
,[lastlogon]
,[employee_id]
,[acc_type]
FROM AD_Users_All_Staging c1
WHERE EXISTS
(
SELECT 1
FROM AD_Users_All_Staging c2
WHERE c2.employee_id = c1.employee_id
GROUP BY
employee_id
HAVING COUNT(1) > 1 -- more than one value
)
a如何仅选择最新记录(lastlogon字段中的值)中存在重复的记录(employee_id字段中的值)
接下来的问题是,如何删除除最新记录之外的每个副本的所有记录
非常感谢因为我没有你的数据,我不能轻易尝试任何东西。。。但是,也就是说,如果您将窗口功能更改为使用
c.lastlogon Desc
而不是Asc,该怎么办。然后,您将始终保留第一条记录Row=1
,并删除其余的Row>1
您可以使用以下命令选择最新的记录:
select uas.*
from AD_Users_All_Staging uas
where not exists (select 1
from AD_Users_All_Staging uas2
where uas2.employee_id = uas.employee_id and
uas2.lastlogon > uas.lastlogon
);
您可以使用反向逻辑执行删除:
select uas.*
from AD_Users_All_Staging uas
where exists (select 1
from AD_Users_All_Staging uas2
where uas2.employee_id = uas.employee_id and
uas2.lastlogon > uas.lastlogon
);
我摸了摸脑袋:
我已经试过了,它似乎给了我它所需要的结果:
;WITH cte AS
(SELECT ROW_NUMBER() OVER(PARTITION BY c1.employee_id ORDER BY c1.lastlogon DESC) AS Row
,[DN]
,[first_name]
,[last_name]
,[init]
,[email]
,[title]
,[display_name]
,[department]
,[phone_num]
,[mob_num]
,[fax_num]
,[pager_num]
,[logon]
,[post_code]
,[www]
,[objectSID]
,[disabled]
,[lastlogon]
,[employee_id]
,[acc_type]
FROM AD_Users_All_Staging c1
WHERE EXISTS
(
SELECT 1
FROM AD_Users_All_Staging c2
WHERE c2.employee_id = c1.employee_id
GROUP BY
employee_id
HAVING COUNT(1) > 1 -- more than one value
)
)
SELECT * FROM cte
WHERE row != 1
这看起来可以吗?当然可以,这基本上就是我的建议。