在SQL中设置重叠百分比

Nic*_*ick 0 sql set overlap

假设SQL数据库中有以下表结构:

Att1   |   Att2   |   Att3   |  Cnt
Run Code Online (Sandbox Code Playgroud)

我想了解Att3对于给定Att1的所有Att2组合的重叠.例如,如果我有下表:

123   |   456    |   abc    |  1
123   |   456    |   efg    |  1
123   |   456    |   hij    |  1
123   |   456    |   klm    |  1
123   |   456    |   nop    |  1
123   |   789    |   efg    |  1
123   |   789    |   abc    |  1
123   |   789    |   xyz    |  1
123   |   789    |   nop    |  1
345   |   456    |   abc    |  1
345   |   456    |   efg    |  1
345   |   789    |   abc    |  1
345   |   999    |   efg    |  1
Run Code Online (Sandbox Code Playgroud)

我会生成以下输出:

123   |   456    |   456    |  1.0
123   |   456    |   789    |  .6
123   |   789    |   456    |  .75
123   |   789    |   789    |  1.0
345   |   456    |   456    |  1.0
345   |   456    |   789    |  .5
345   |   456    |   999    |  .5
345   |   789    |   456    |  1.0
345   |   789    |   789    |  1.0 
345   |   789    |   999    |  0
345   |   999    |   456    |  1.0
345   |   999    |   789    |  0  
345   |   999    |   999    |  1.0
Run Code Online (Sandbox Code Playgroud)

我知道使用SQL可能不是最好的方法,所以我很高兴听到其他选择,但SQL是我目前拥有数据的地方.

Pin*_*nyM 5

你可以使用聚合的一些简单技巧来做到这一点:

SELECT t1.att1, t1.att2, t2.att2 as att2_other, 
       SUM(CASE WHEN t2.att3 = t1.att3 THEN 1.0 ELSE 0 END)/COUNT(DISTINCT t1.att3) as Cnt
FROM table_name t1
JOIN table_name t2
  ON t1.att1 = t2.att1
GROUP BY t1.att1, t1.att2, t2.att2
Run Code Online (Sandbox Code Playgroud)

在这里工作sqlfiddle