简体   繁体   English

sql比较一个表中两个不同的组列的不同值

[英]sql for compare two distinct group column different values in one table

Suppose one table t as following: 假设一个表t如下:

c1 c2
    == ==
    a  1
    a  2
    b  1
    b  2
    b  3
    c  4
    c  2

We group this table by c1 and has three group a, b, c. 我们将此表按c1分组,并具有三个组a,b,c。 I need calculate the similarity of column c2 between two groups, like the following: 我需要计算两组之间的列c2相似度,如下所示:

sim(a,b) = 2(common value of c2 are 1 and 2)/3(all value)=2/3
    sim(b,c) = 1(b and c has only one value 2 in common)/4 = 1/4
    sim(a,c) = 1/3

Can we use sql(Oracle 11g syntax first) to construct the expression above? 我们可以使用sql(首先使用Oracle 11g语法)来构造上面的表达式吗?

I believe this query does what you want: 我相信此查询可以满足您的要求:

select t1.c1, t2.c1, count(*) as NumInCommon,
       (select count(distinct t.c2)
        from t
        where t.c1 in (t1.c1, t2.c1)
       ) as NumInTotal
from t t1 join
     t t2
     on t1.c2 = t2.c2
group by t1.c1, t2.c1

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

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