• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 28
  • Last Modified:

Removing a transposed record

I have a table with two fields in it, Contact and RelatedContact.  
The first two records look like this:

ID  Contact   RelatedContact
1    1000        7000
2    7000        1000

I need to have just one record in this table, doesn't matter which one.  I can't have two records
in this table that are the reverse of each other.  How can I eliminate one of them?
1 Solution
Martin MillerCTOCommented:
Typically you would do something like this, shown below, where you insert the table_name and column_name. A row deletion example follows.

For a column:
ALTER TABLE "table_name" DROP "column_name";

Open in new window

For a row:

DELETE FROM "table_name"  WHERE "column_name"  = 'SOME_MATCH_STRING_OR_VALUE';

Open in new window

Let me know if you have other questions
nolasaintsgalAuthor Commented:
Sorry I don't believe I was clear enough.  This table will have multiple records where they will appear transposed:

ID  Contact  RelatedContact
1   1000        1007
2   1007        1000
3   2000        1004
4   1004        2000

So I need something where it will look at first record and see that there is a second record with the values transposed and delete one of those transposed records.  So in this instance, records 2 and 4 could be deleted because are equal to records 1 and 3, respectively, when transposed.
Scott PletcherSenior DBACommented:
Do two things:
1) Delete all the dups
2) Add a constraint that the Contact value must be less than the RelatedContact value, and the combination of the two must be unique.  Then you can never get dups values like that again.

No data to test with, so this is "air' code in a sense:

FROM dbo.table_name tn
WHERE Contact > RelatedContact AND
    EXISTS (
        SELECT 1
        FROM dbo.table_name tn2
            tn2.Contact < tn2.RelatedContact AND
            tn2.Contact = tn.RelatedContact AND
            tn2.RelatedContact = tn.Contact )

ALTER TABLE dbo.table_name
ADD CONSTRAINT table_name__CK_Contacts CHECK(Contact < RelatedContact);
ALTER TABLE dbo.table_name
ADD CONSTRAINT table_name__UQ_Contacts UNIQUE ( Contact, RelatedContact );
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now