2015-11-06 80 views
1

我有一個表下面,我想選擇所有獨特的對。很難說這個問題沒有聽起來像我只需要select distinct,所以我會寫出所需的輸出和每個可能的組合。postgreSQL中的組合 - 選擇對

enter image description here

Pair1:(1,4)和(2,5)

Pair2:(1,4)和(3,6)

Pair3:(2,5)和(3,6)

這是一樣的二項式係數:

ñ選擇R,其中N = 3且k = 2

理想情況下,輸出將類似於:

enter image description here

老實說,我不知道這一個開始,所以請原諒,沒有第一次嘗試。有條件的消除重複

回答

3

使用自聯接:

create table a_table (cola int, colb int); 
insert into a_table values 
(1, 4), (2, 5), (3, 6); 

select * 
from a_table a 
join a_table b 
on a.cola < b.cola and a.colb <> b.colb; 

cola | colb | cola | colb 
------+------+------+------ 
    1 | 4 | 2 | 5 
    1 | 4 | 3 | 6 
    2 | 5 | 3 | 6 
(3 rows) 

上面的查詢工作得很好,如果列cola是獨一無二的。 如果cola值可以重來,你應該添加一個附加條件:

insert into a_table values (1, 8); 

select * 
from a_table a 
join a_table b 
on a.cola < b.cola and a.colb <> b.colb 
or a.cola = b.cola and a.colb < b.colb 
order by 1, 2; 

cola | colb | cola | colb 
------+------+------+------ 
    1 | 4 | 2 | 5 
    1 | 4 | 3 | 6 
    1 | 4 | 1 | 8 
    1 | 8 | 2 | 5 
    1 | 8 | 3 | 6 
    2 | 5 | 3 | 6 
(6 rows) 
+0

似乎是正確的,現在:) – jpw

+0

對於一般的解決方案,在這裏你需要選擇一些任意子集,而不僅僅是對,你可以使用在目標表上進行自連接的遞歸CTE。 –