如何计算 SQL 中项目的常用用法?

How to count common usage of items in SQL?

我想统计公司之间有多少共同的项目,比如:

Company Participation
Apple Project 1
Microsoft Project 1
Tesla Project 2
Apple Project 2
Microsoft Project 2

SQL 中是否有简单易行的方法?这样的输出?

Apple Microsoft Tesla
Microsoft 2 1
Tesla 1 1
Apple 2 1

有一个简单的方法,但是 - 输出并不完全如您所愿。它显示了对和共同项目的数量(cnt 列):

SQL> select a.company, b.company, count(distinct b.participation) cnt
  2  from project a join project b on a.company < b.company
  3  group by a.company, b.company;

COMPANY   COMPANY          CNT
--------- --------- ----------
Apple     Tesla              1
Apple     Microsoft          2
Microsoft Tesla              1

SQL>

可以在数据透视表的源查询中执行 self-join。

SELECT *
FROM (
  SELECT t1.Company
  , t2.Company AS Company2
  , COUNT(t1.Participation) AS Participations
  FROM CompanyProjectParticipations t1
  JOIN CompanyProjectParticipations t2
    ON t2.Participation = t1.Participation
   AND t2.Company != t1.Company
  GROUP BY t1.Company, t2.Company
) Src
PIVOT (
  SUM(Participations)
  FOR Company2 IN ([Apple], [Microsoft], [Tesla])
) Pvt
ORDER BY Company;
Company Apple Microsoft Tesla
Apple null 2 1
Microsoft 2 null 1
Tesla 1 1 null

测试 db<>fiddle here