计算SQL中的对数

时间:2015-06-26 12:08:35

标签: sql

我有一个列,我想计算SQL中列中元素的唯一配对数,例如,在第1列中,唯一配对的数量应为6:([1,2],[ 1,3],[1,4],[2,3],[2,4],[3,4])。谢谢!

    col 1,
    1
    2
    3
    4

2 个答案:

答案 0 :(得分:2)

考虑一下这样一个场景:我们在表格中表达了多少值

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;

要修改此缺陷,我有以下查询,确保删除重复项并获得正确的输出。我选择的表名是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 :(得分:1)

有两种方法。繁琐的方法是生成对,然后计算它们:

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

更简单的方法是使用公式:

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