通过其他列查找同一行SQL上的连接

时间:2017-04-12 13:06:24

标签: mysql

我在MySQL中找到解决方案时遇到了一些问题。我想创建一个查询,该查询可以计算一行中两个不同的值在不同列中具有相同值的时间。

更具体地说,我想找到两位发明家在同一专利上合作的次数。我在excel中手动创建了输出,但在SQL代码中没有解决方案。

我的表格如下:

Patent      Inventor
04412478    D0456998-2
04926296    D0456998-2
05597593    D0456998-1
06267663    07225494-3
06299015    07225494-3
06299015    D0456998-1
06301919    07225494-3
06301919    D0456998-1
06311837    D0456998-1
06311837    D0456998-2
06360395    07225494-3
06360395    D0456998-1
06360395    D0456998-2
06371294    07225494-3
06371294    D0456998-1
06371294    D0456998-2
06546585    D0456998-1
06546585    D0456998-2
06663482    07225494-3
06988292    06245813-3
06988292    06877638-0
D0437469    07225494-3
D0465088    07225494-3
D0465088    D0456998-1
D0465088    D0456998-2

这将是查询的输出:

Inventor 1  Inventor 2  Collaborations
06245813-3  06877638-0  1
07225494-3  D0456998-1  5
07225494-3  D0456998-2  3
D0456998-1  D0456998-2  5

我该如何解决这个问题?非常感谢任何建议或帮助!

1 个答案:

答案 0 :(得分:0)

SELECT x.inventor inventor1
     , y.inventor inventor2
     , COUNT(*) total
  FROM my_table x 
  JOIN my_table y 
    ON y.patent = x.patent 
   AND y.inventor < x.inventor 
 GROUP
    BY x.inventor
     , y.inventor;