根据Oracle

时间:2017-06-21 00:43:50

标签: sql database oracle duplicates sql-delete

我想根据条件从表中删除重复的行。

如, 表ABC:

ID  Name    Pin Status
111 Pope    909 New
222 Jazz    909 New
333 Volk    767 Assigned
444 Audi    767 New
555 Pink    435 New

我想删除具有相同' Pin'的重复记录。基于以下条件:

  1. 如果两个相同的Pin记录都具有新状态 - 删除其中任何一个。
  2. 如果其中一个相同的Pin记录具有“新状态”而另一个具有“已分配状态” - 请删除“新建”状态。状态记录。
  3. 我写了下面的SQL,但我想知道是否有更好的方法来处理这个使用PK。

    1:

    DELETE FROM ABC WHERE ID IN (
    SELECT
      a.id
    FROM ABC a
    WHERE a.rowid <
      (SELECT max(rowid)
      FROM  ABC  b
      WHERE b.pin = a.pin
      AND a.status  = b.status
      AND b.status  in ('New')
      )
    );
    

    2:

    DELETE FROM ABC WHERE ID IN (
    SELECT
      a.id
    FROM ABC a
    WHERE a.rowid <
      (SELECT max(rowid)
      FROM  ABC  b
      WHERE b.pin = a.pin
      AND a.status  <> b.status
      AND a.status  in ('New')
      AND b.status  in ('Assigned')
      )
    );
    

3 个答案:

答案 0 :(得分:0)

你可以试试这个。

--Query 1:
DELETE FROM ABC
WHERE ID NOT IN (SELECT MIN(ID)
                 FROM ABC 
                 GROUP BY Pin
                 HAVING COUNT(*)=COUNT(CASE WHEN status = 'New' THEN 1 END)
                );

--Query 2:
DELETE FROM ABC
WHERE ID IN (SELECT ID
             FROM ABC A
             WHERE status = 'New'
             AND EXISTS (SELECT 1 FROM ABC B 
                         WHERE A.Pin=B.Pin AND B.status='Assigned')

            );

答案 1 :(得分:0)

如果每个pin最多有两条记录:

DELETE FROM ABC
WHERE rowid IN (SELECT MIN(CASE WHEN a.status = 'NEW' then rowid END) 
                FROM ABC a
                WHERE abc.pin = a.pin AND
                      a.status IN ('New', 'Assigned'
                GROUP BY a.pin
                HAVING COUNT(*) > 1
               );

答案 2 :(得分:0)

尝试此查询 -

-- Select ID, Name, Pin, Status
Delete
From (
    Select  
        ID, Name, Pin, Status,
        Row_Number() Over(Partition By Pin Order By Pin) As PinRowNum,
        Row_Number() Over(Partition By Pin, Status Order By Status) As 
    StatusRowNum
From ABC
) As D Where StatusRowNum > 1 Or (PinRowNum > 1 And StatusRowNum = 1)