2015-06-26 58 views
-1

我有一列,我想計算SQL中列中元素的唯一配對數量,例如,在第1列中,唯一配對的數量應爲6 :([1,2],[1,3],[1,4],[2,3],[2,4],[3,4])。謝謝!計算SQL中對的數量

col 1, 
    1 
    2 
    3 
    4 
+0

哪個DBMS?你嘗試了什麼? –

+0

[返回SQL中單個列中所有可能的值組合值]的可能重複(http://stackoverflow.com/questions/31070337/return-all-possible-combinations-of-values-within-a-single-column -in-SQL) – jarlh

回答

2

考慮這樣一個場景,在我們在表dulpicates值說

col1 
1 
1 
2 
3 
4 
5 

唯一組合的總數是10:([1,2],[1,3],[1,4],[1,5],[2,3],[2,4 ],[2,5],[3,4] [3,5],[4,5])。

但是,下面的給出的查詢給了我14的計數,因爲dulplicate 1計數了4對額外的[1,2],[1,3],[1,4],[1,5]兩次。

select count(*) 
from table t1 join 
table t2 
on t1.col1 < t2.col1; 

要修改這一缺陷,我有以下查詢這確保了重複被刪除,我們得到我選擇了正確的output.The表名是COUNTUNIQUE可以在它指定的列COL1存儲整數值。

select count(*) from 
(select distinct col1 from countunique) t1 
join (select distinct col1 from countunique) t2 
on t1.col1<t2.col1 

SQL小提琴,供您參考SQLFIDDLE

希望這回答了你的問題。

1

有兩種方法。繁瑣的方式是產生對,然後指望他們:

select count(*) 
from table t1 join 
    table t2 
    on t1.col1 < t2.col1; 

更簡單的方法是使用一個公式:

select count(*) * (count(*) - 1)/2 
from table t;