首页 > 解决方案 > 如何从 2 个重复行中只删除一行?

问题描述

我在表中有 2 行重复,我只想从中删除 1 行并保留另一行。我该怎么做?

标签: mysqlsqlpostgresql

解决方案


PostGres 代码可能有点不同,但这里有一个来自 TSQL 的示例,它使用 CTE 执行此操作:

; WITH duplicates
AS (
    SELECT ServerName ,
           ProcessName ,
           DateCreated ,
           RowRank = ROW_NUMBER() OVER(PARTITION BY ServerName, ProcessName, DateCreated ORDER BY 1)
    FROM dbo.ErrorLog
    )
DELETE e
FROM dbo.ErrorLog e
    JOIN duplicates d
        ON d.ServerName = e.ServerName
        AND d.ProcessName = e.ProcessName
        AND d.DateCreated = e.DateCreated
        AND d.RowRank <> 1

推荐阅读