简体   繁体   English

在SQL中选择不同的值对

[英]selecting distinct pairs of values in SQL

I have an Access 2010 database which stores IP addresses of source and destination machines. 我有一个Access 2010数据库,它存储源和目标计算机的IP地址。 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). 列出源/目的地对时,您只想在一个方向上看到对,例如,(A,B)但不是(B,A)。

  2. The list should omit pairs where the source and destnation are the same, eg, (D,D) 该列表应该省略源和destnation相同的对,例如,(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... ...当针对包含......的[SomeTable]运行时...

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 从YourTable中选择唯一的源,目的地

or 要么

select distinct source, destination from YourTable 从YourTable中选择不同的源,目的地

or 要么

select source, destination from YourTable group by source, destination 按源,目标从YourTable组中选择源,目标

Use GROUP BY clause 使用GROUP BY子句

SELECT  source, destination 
FROM SomeTable
GROUP BY source, destination 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM