选择唯一的列组合

时间:2013-09-16 08:26:30

标签: sql sql-server

我有下表:

create table cric_country
(
id int,
country varchar (20)
)
insert into cric_country values
(1,'Ind'),(2,'Aus'),(3,'NZ')

我需要为需要2列国家/地区的国家/地区获取播放装置,并且应省略相同的国家/地区并重复匹配: 我写了以下查询:

select
t1.country,t2.country
from cric_country t1
inner join
cric_country t2
on t1.country <> t2.country

但它没有解决目的,因为我有Aus / Ind以及Ind / Aus,需要省略一个但不能做一个明确的。

2 个答案:

答案 0 :(得分:2)

SELECT a.country country1, b.country country2
FROM   cric_country a
       CROSS JOIN cric_country b
WHERE  a.country < b.country
ORDER  BY a.country, b.country

输出

╔══════════╦══════════╗
║ COUNTRY1 ║ COUNTRY2 ║
╠══════════╬══════════╣
║ Aus      ║ Ind      ║
║ Aus      ║ NZ       ║
║ Ind      ║ NZ       ║
╚══════════╩══════════╝

答案 1 :(得分:1)

很简单:

SELECT t1.country c1, t2.country c2
  FROM cric_country t1 JOIN cric_country t2 ON t1.id > t2.id;