selecting distinct pairs of values in SQL

2019-02-14 14:00发布

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     |

3条回答
狗以群分
2楼-- · 2019-02-14 14:43

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          
查看更多
smile是对你的礼貌
3楼-- · 2019-02-14 14:47

select unique source, destination from YourTable

or

select distinct source, destination from YourTable

or

select source, destination from YourTable group by source, destination

查看更多
再贱就再见
4楼-- · 2019-02-14 14:55

Use GROUP BY clause

SELECT  source, destination 
FROM SomeTable
GROUP BY source, destination 
查看更多
登录 后发表回答