1

I am accessing table that takes in every encounter between two vehicles (i do not have permissions to change this table). When an encounter occurs, it'll take in one row for each perspective of the encounter- Vehicle X encountered Vehicle Y and another row for Vehicle Y encountered Vehicle X. Here's some sample data:

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

There are no duplicates in any row, values are all unique. But every value in Vehicle1 exists in vehicle2. How would i get it so only one of each pair exists?

3
  • Are there always (a,b), (b,a) pairs and no other? Commented Dec 11, 2018 at 16:15
  • Do you have an ID column for referencing? Commented Dec 11, 2018 at 16:21
  • yes, it's only a,b and b,a pairs and there's no columns that don't look similar to this. Commented Dec 11, 2018 at 16:22

1 Answer 1

2

GREATEST and LEAST functions might help. DELETE ... USING syntax

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;
Sign up to request clarification or add additional context in comments.

3 Comments

This looks like it works! Any chance you could explain what exactly is happening in this? I'm still newish to postgresql and am curious.
There is a couple of thing going on here. a) The subquery finds the duplicates. It does it by sorting two columns: vehicle1 will have the greatest of the two and vehicle2 will have the least. Now the rows would be identical (they will have same value for vehicle1 and vehicle2, so you can find the duplicates using having count(*) > 1 b) the delete query then uses all three fields as a primary key to delete the rows. It will leave the other one alive because values for vehicle1 and vehicle2 are switched. Hope this helps.
Wow, so it becomes like an inter-column sort. Thanks for the explanation!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.