8 Jul 2013

Remove rows having swapped column values in SQL Server

I have a table like
+ ----------------------- +
| RowID | FromCol | toCol |
+ ----------------------- +
| 1     | a       | b     |
| 2     | b       | c     |
| 3     | c       | d     |
| 4     | c       | b     |
| 5     | b       | a     |
+ ----------------------- +
I would like to remove the rows that has FromCol --> ToCol same value as ToCol --> FromCol For eg. RowID 1 is a-->b and RowID 5 has b-->a so rowID 5 should be removed. Similarly RowID 4 should be removed because it has a swapped value like RowID 2.
My expected result Table is:
+ ----------------------- +
| RowID | FromCol | toCol |
+ ----------------------- +
| 1     | a       | b     |
| 2     | b       | c     |
| 3     | c       | d     |
+ ----------------------- +

Above can be achieved by the below query
 
select t1.*
FROM dbo.MyTest t1
WHERE (SELECT COUNT(t2.rowid) 
         FROM dbo.MyTest t2 
        WHERE t2.toCol= t1.fromCol
          AND t2.fromCol= t1.toCol
          AND t1.rowid> t2.rowid) = 0 

No comments:

Post a Comment