sql server—sql中多列的成对交叉计数

t98cgbkg  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(282)

假设我有一个包含多个表的sqldb,每个表都有一列 code . 我要生成的是一个表,显示每对代码之间共享的代码数 code 柱。i、 e.成对交叉点计数图:

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

但是,是否有一个查询可以按表的形式生成整个输出?

qvtsj1bj

qvtsj1bj1#

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

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 .

相关问题