Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

selecting distinct pairs of values in SQL

I have an Access 2010 database which stores IP addresses of source and destination machines. If I have the following entries in my database

|source           |   destination|
|--------------------------------|
|  A              |     B        |
|  B              |     A        |
|  A              |     B        |
|  C              |     D        |
|  D              |     D        |

Is there any query to select unique pairs? That is, the output of the query should be

|source           |     destination|
|----------------------------------|
|  A              |          B     |
|  C              |          D     |
like image 925
Swamy Avatar asked Mar 22 '23 03:03

Swamy


1 Answers

Your question seems to imply two things:

  1. When listing source/destination pairs you only want to see the pairs in one direction, e.g., (A,B) but not (B,A).

  2. The list should omit pairs where the source and destnation are the same, e.g., (D,D)

In that case the query...

SELECT DISTINCT source, destination
FROM
    (
            SELECT source, destination
            FROM SomeTable
        UNION ALL
            SELECT destination, source
            FROM SomeTable
    )
WHERE source < destination

...when run against [SomeTable] containing...

source  destination
------  -----------
A       B          
B       A          
A       B          
C       D          
D       D          
E       D          

...will produce:

source  destination
------  -----------
A       B          
C       D          
D       E          
like image 142
Gord Thompson Avatar answered Mar 31 '23 22:03

Gord Thompson