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]). 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]).
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.
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.
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
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.