gpt4 book ai didi

sql - 删除 SQL 中的重复行

转载 作者:行者123 更新时间:2023-12-05 00:13:33 25 4
gpt4 key购买 nike

我有一个具有唯一 ID 但重复行信息的表。

我可以使用此查询找到重复的行

SELECT
PersonAliasId, StartDateTime, GroupId, COUNT(*) as Count
FROM
Attendance
GROUP BY
PersonAliasId, StartDateTime, GroupId
HAVING
COUNT(*) > 1

我可以手动删除行,同时保留此查询所需的 1
Delete
From Attendance
Where Id IN(SELECT
Id
FROM
Attendance
Where PersonAliasId = 15
and StartDateTime = '9/24/2017'
and GroupId = 1429
Order By ModifiedDateTIme Desc
Offset 1 Rows)

我对 SQL 不够精通,无法弄清楚如何使用第一个查询中的行来删除留下最新的重复项。第一个查询返回的记录超过 3481 条,手动一个一个。

如何找到像第一个查询一样的重复行并像第二个查询一样删除除最近的所有行?

最佳答案

您可以使用 Common Table Expression 删除重复项:

WITH Cte AS(
SELECT *,
Rn = ROW_NUMBER() OVER(PARTITION BY PersonAliasId, StartDateTime, GroupId
ORDER BY ModifiedDateTIme DESC)
FROM Attendance
)
DELETE FROM Cte WHERE Rn > 1;

这将保留每个 PersonAliasId - StartDateTime - GroupId 的最新记录。组合。

关于sql - 删除 SQL 中的重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48406742/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com