简体   繁体   中英

How to compare two different column for opposite of one another in mssql

I have a result set that is a relationship table. I am converting their data from one schema to another. There relationship table as a relationship row for each person. so for example if bill knows bob there is a row that has contactid and contactid1.

Contactid being the primary person in the relationship. In their system Bob would need to have a separate row with him being the primary.

so the rows in their DB would look like this

Contactid | Contactid1 | Description
123       | 456        |Gold Club Dinner
456       | 123        |Gold Club Dinner

Whereas in my schema the relationship looks like this

Contactid | Contactid1 | Description
123       | 456        |Gold Club Dinner

I need to know a way to get the top 1 for each group in the first db so that I don't end up with thousands of duplicates in the table structure.

Any ideas?

Try this

select distinct
    case when contactID<contactID1 then contactID else contactID1 end , 
    case when contactID<contactID1 then contactID1 else contactID end ,
    description
from yourtable

I would argue, however, that both these designs are wrong, and should be normalised.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM