selecting distinct pairs of values in SQL

怎甘沉沦 提交于 2019-11-30 21:52:59

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          

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 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!