简体   繁体   English

计算SQL中的对数

[英]Count the number of pairs in SQL

I have a column and I would like to count the number of unique pairings of the elements within the column in SQL, for example, in Col 1 the number of unique pairings should be 6: ([1,2],[1,3],[1,4],[2,3],[2,4],[3,4]). 我有一列,我想计算SQL中该列中元素的唯一配对数,例如,在第1列中,唯一配对数应为6:([[1,2],[1,3 ],[1,4],[2,3],[2,4],[3,4])。 Thanks! 谢谢!

    col 1,
    1
    2
    3
    4

Consider a scenario where in we have dulpicates values in the table say 考虑一个场景,其中我们在表中加了重复值

col1
1
1
2
3 
4
5

The total number of unique combinations is 10:([1,2],[1,3],[1,4],[1,5],[2,3],[2,4],[2,5],[3,4][3,5],[4,5]). 唯一组合的总数为10:([1,2,3,[1,3],[1,4],[1,5],[2,3],[2,4],[2,5 ],[3,4] [3,5],[4,5])。

But the given query below is giving me a count of 14 because of the dulplicate 1 which is counting 4 extra pairs [1,2],[1,3],[1,4],[1,5] twice. 但是下面给出的查询给了我14个计数,因为重复1重复计数了4个额外的对[1,2],[1,3],[1,4],[1,5]。

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

To modify this defect I have the following query which ensures that the duplicates are removed and we get the correct output.The table name I have chosen is countunique which can store integer values in it in column named 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 for your reference SQLFIDDLE SQL Fiddle供您参考SQLFIDDLE

Hope this answers to your question. 希望这能回答您的问题。

There are two ways. 有两种方法。 The cumbersome way is to generate the pairs and then count them: 麻烦的方法是生成对,然后计算它们:

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

The simpler way is to use a formula: 比较简单的方法是使用公式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM