简体   繁体   中英

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     |

Your question seems to imply two things:

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

  2. The list should omit pairs where the source and destnation are the same, eg, (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          

select unique source, destination from YourTable

or

select distinct source, destination from YourTable

or

select source, destination from YourTable group by source, destination

Use GROUP BY clause

SELECT  source, destination 
FROM SomeTable
GROUP BY source, destination 

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