使用列组合删除Oracle中的重复行[Complex]

时间:2016-01-14 11:41:07

标签: sql oracle duplicates

我有下表

City1   City2
NY      TO
TO      ON
TO      NY
TO      AT
AT      TO
TO      AT

问题认为NY-TO和TO-NY是重复的,需要在Oracle中查询以查找和删除上面提到的重复行。不要考虑TO-AT& TO-AT重复。试过几种方式,即子查询,自连接等。但无法解决。有人在这里查询科学家吗?

3 个答案:

答案 0 :(得分:0)

SELECT ct1.id 
FROM city_table ct1
     JOIN city_table ct2 ON CONCAT(ct1.city1+ct1.city2)=CONCAT(ct2.city1+ct2.city2)
OR CONCAT(ct1.city2+ct1.city1)=CONCAT(ct2.city1+ct2.city2)

您可以将JOIN基于两个城市的连接

如果rec1的city1+city2city1+city2city2+city1或rec2

相同,则

记录相同

答案 1 :(得分:0)

假设您有某种方式对表进行排序(即通过主键或时间戳):

CREATE TABLE table_name ( id, city1, city2 ) AS
SELECT 1, 'NY', 'TO' FROM DUAL UNION ALL
SELECT 2, 'TO', 'ON' FROM DUAL UNION ALL
SELECT 3, 'TO', 'NY' FROM DUAL UNION ALL
SELECT 4, 'TO', 'AT' FROM DUAL UNION ALL
SELECT 5, 'AT', 'TO' FROM DUAL UNION ALL
SELECT 6, 'TO', 'AT' FROM DUAL;

然后你可以这样做:

DELETE FROM table_name
WHERE  ROWID IN (
  SELECT ROWID
  FROM   (
    SELECT CASE city1
             WHEN FIRST_VALUE( city1 )
                    OVER ( PARTITION BY LEAST( City1, City2 ),
                                        GREATEST( City1, City2 )
                           ORDER BY id )
             THEN 0
             ELSE 1
           END AS to_delete
    FROM table_name
  )
  WHERE  to_delete = 1
)

将离开:

ID | C1 | C2 
-------------
 1 | NY | TO
 2 | TO | ON
 4 | TO | AT
 6 | TO | AT

答案 2 :(得分:0)

如果我正确解释了您的请求,这可能是一个解决方案:

DELETE FROM your_table WHERE ROWID IN (SELECT ID FROM (SELECT ROWID ID, ROW_NUMBER() OVER(PARTITION BY city1, city2 ORDER BY city1, city2) num FROM your_table) WHERE num > 1)

否则,您能否举例说明您需要的结果。