1

假设我有一个包含多个表的 SQL 数据库,并且每个表都有一个 column code。我想要生成的是一个表格,显示了每对code列之间共享的代码数量。即成对的交点计数图:

       table1 table2 table3 table4
table1     10      2      3      5
table2      2     10      4      1
table3      3      4     10      2
table4      5      1      2     10

我可以使用例如单独获取每个值

WITH abc AS 
(
SELECT code FROM table1
INTERSECT
SELECT code FROM table2
)

SELECT COUNT(*) AS table1Xtable2 FROM abc

但是是否有一个查询可以根据需要生成整个输出作为表?

4

1 回答 1

3

以下获取表中的所有组合:

select t1, t2, t3, t4, count(*) 
from (select code, max(t1) as t1, max(t2) as t2, max(t3) as t3, max(t4) as t4
      from ((select code, 1 as t1, 0 as t2, 0 as t3, 0 as t4
             from table1
            ) union all
            (select code, 0 as t1, 1 as t2, 0 as t3, 0 as t4
             from table2
            ) union all
            (select code, 0 as t1, 0 as t2, 1 as t3, 0 as t4
             from table3
            ) union all
            (select code, 0 as t1, 0 as t2, 0 as t3, 1 as t4
             from table4
            )
           ) t
      group by code
     ) t
group by t1, t2, t3, t4;

对于您的特定问题,您可以使用:

with t as (
      select code, 'table1' as tablename from table1 union all
      select code, 'table2' as tablename from table2 union all
      select code, 'table3' as tablename from table3 union all
      select code, 'table4' as tablename from table4 
     )
select t1.tablename,
       sum(case when t2.tablename = 'table1' then 1 else 0 end) as t1,
       sum(case when t2.tablename = 'table2' then 1 else 0 end) as t2,
       sum(case when t2.tablename = 'table3' then 1 else 0 end) as t3,
       sum(case when t2.tablename = 'table4' then 1 else 0 end) as t4
from t t1 join
     t t2
on t1.code = t2.code
group by t1.tablename

请注意,以上假设code在表中是唯一的。如果重复,可以替换union allunion.

于 2020-06-01T11:49:09.043 回答