[英]Count the number of pairs in SQL
我有一列,我想計算SQL中該列中元素的唯一配對數,例如,在第1列中,唯一配對數應為6:([[1,2],[1,3 ],[1,4],[2,3],[2,4],[3,4])。 謝謝!
col 1,
1
2
3
4
考慮一個場景,其中我們在表中加了重復值
col1
1
1
2
3
4
5
唯一組合的總數為10:([1,2,3,[1,3],[1,4],[1,5],[2,3],[2,4],[2,5 ],[3,4] [3,5],[4,5])。
但是下面給出的查詢給了我14個計數,因為重復1重復計數了4個額外的對[1,2],[1,3],[1,4],[1,5]。
select count(*)
from table t1 join
table t2
on t1.col1 < t2.col1;
要修改此缺陷,我有以下查詢,確保刪除重復項並獲得正確的輸出。我選擇的表名是countunique,可以在其中將整數值存儲在名為col1的列中。
select count(*) from
(select distinct col1 from countunique) t1
join (select distinct col1 from countunique) t2
on t1.col1<t2.col1
SQL Fiddle供您參考SQLFIDDLE
希望這能回答您的問題。
有兩種方法。 麻煩的方法是生成對,然后計算它們:
select count(*)
from table t1 join
table t2
on t1.col1 < t2.col1;
比較簡單的方法是使用公式:
select count(*) * (count(*) - 1) / 2
from table t;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.