T-Sql Query - Get Unique Rows Across 2 Columns

sql, t-sql

Solution

Add to your query the predicate,

where X < Y

and you can never get row two, but will always get row one.

(This assumes that when you wrote "two given values" you meant two distinct given values; if the two values can be the same, add the predicate `where X <= Y` (to get rid of all "reversed" rows where X > Y) and then add a `distinct` to your select list (to collapse any two rows where X == Y into one row).)

In reply to comments:

That is, if currently your query is `select foo, x, y from sometable where foo < 3;` change it to `select foo, x, y from sometable where foo < 3 and x < y;`, or for the the second case (where X and Y are not distinct values) `select distinct foo, x, y from sometable where foo < 3 and x <= y;`.

Problem

I have a set of data, with columns x and y. This set contains rows where, for any 2 given values, A and B, there is a row with A and B in columns x and y respectivly and there will be a second row with B and A in columns x and y respectivly. E.g ``` **Column X** **Column Y** Row 1 A B Row 2 B A ``` - There are multiple pairs of data in this set that follow this rule. - For every row with A, B in Columns X and Y, there will always be a row with B, A in X and Y - Columns X and Y are of type int I need a T-Sql query that given a set with the rules above will return me either Row 1 or Row 2, but not both. Either the answer is very difficult, or its so easy that I can't see the forest for the trees, either way it's driving me up the wall.

Original source