[英]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.