【问题标题】:How to delete only a single row from 2 duplicate rows?如何从 2 个重复行中只删除一行?
【发布时间】:2018-05-31 16:04:55
【问题描述】:

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

【问题讨论】:

  • 您可以先向我们展示示例数据以及您希望保留一行而不是另一行的逻辑。
  • 保留哪一行重要吗?
  • 如果它们是完全重复的,那么您需要限制删除的行数。据我所知,postgresql 不支持limitdelete。看看这个问题的答案以获得一些想法:How do I delete a fixed number of rows with sorting in PostgreSQL?
  • 您使用的是 MySQL 还是 Postgres?它们不是一回事。
  • 正确标记!!! MySQL Postgres!!!

标签: mysql sql postgresql


【解决方案1】:

PostGres 代码可能有点不同,但这里有一个使用 CTE 的 TSQL 示例:

; 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-08
    • 2021-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-09
    • 2017-12-04
    • 2022-01-18
    相关资源
    最近更新 更多