从多个唯一列中删除重复项

时间:2018-12-11 16:11:17

标签: postgresql

我正在访问包含两辆车之间每次相遇的表(我无权更改此表)。发生相遇时,相遇的每个视角都将排成一排-车辆X遇到车辆Y,而车辆Y的另一行遇到车辆X。这是一些示例数据:

Location  Vehicle1  Vehicle2
103923    5594800   54114
105938    40547     1855442
103923    2588603   5659158
103923    54114     5594800
103923    5659158   2588603
105938    1855442   40547

任何行中都没有重复项,值都是唯一的。但是Vehicle1中的每个值都存在于vehicle2中。我怎么会这样,所以每对中只有一个存在?

1 个答案:

答案 0 :(得分:2)

GREATEST and LEAST函数可能会有所帮助。 DELETE ... USING语法

DELETE
FROM t a USING
  ( SELECT location, 
           greatest(Vehicle1 , Vehicle2) as vehicle1, 
           least(Vehicle1 , Vehicle2) as vehicle2
   FROM t
   GROUP BY 1,2,3 HAVING COUNT(*) > 1 ) b
WHERE a.location = b.location
  AND a.Vehicle1 = b.Vehicle1
  AND a.Vehicle2 = b.Vehicle2;