匹配多个表的值

时间:2017-08-15 23:05:34

标签: sql sql-server sql-server-2012

我有一个包含6个表的SQL Server数据库。

在这些表格中有一种客户名称。

  • 表一:Forename,Surname
  • 表二:名字,第二名
  • 表三:FirstName,Surname
在6个表中等等。

我要做的是计算多少次:

  • 所有表格中都会显示全名(名字和姓氏的CONCAT)。
  • 5个表格中显示全名(名字和姓氏的CONCAT)
  • 4个表格中显示全名(名字和姓氏的CONCAT) 等等。
  • 全名(名字和姓氏的CONCAT)仅出现在表1

在SQL中有一种简单的方法可以做这种类型的事情吗?

由于

2 个答案:

答案 0 :(得分:1)

我想你想要一个union allgroup by。以下内容比您要求的要多一些。它返回名称在每个表中出现的次数。

如果您愿意,可以轻松简化表格计数:

select t1, t2, t3, t4, t5, t6, count(*) as cnt,
       min(fullname), max(fullname)
from (select fullname,
             sum(t1) as t1, sum(t2) as t2, sum(t3) as t3, sum(t4) as t4,
             sum(t5) as t5, sum(t6) as t6
      from ((select firstname +  ' ' + lastname as fullname,
                    1 as t1, 0 as t2, 0 as t3, 0 as t4, 0 as t5, 0 as t6
             from t1
            ) union all
            (select firstname +  ' ' + lastname as fullname,
                    0 as t1, 1 as t2, 0 as t3, 0 as t4, 0 as t5, 0 as t6
             from t2
            ) union all
            . . .
           ) t
       group by fullname
      ) f
group by t1, t2, t3, t4, t5, t6;

答案 1 :(得分:0)

也许就是这样。

Select Name
      ,Hits=count(*)
      ,Tables = count(distinct Src)
 From (
        Select Src='Table1',Name=concat(FirstName,LastName) From Table1
        Union All
        Select Src='Table2',Name=concat(Foreame,SurName) From Table2
        Union All
        Select Src='Table3',Name=concat(FirstName,SurName) From Table3
        Union All
        ... Add more tables here
     ) A
 Group By Name
 Having count(*)>1
  

编辑 - 工作样本或dbFiddle

Declare @Table1 table (FirstName varchar(50),LastName varchar(50))
Insert Into @Table1 values
 ('John','Smith')
,('Mary','Smith')

Declare @Table2 table (ForeName varchar(50),SurName varchar(50))
Insert Into @Table2 values
 ('John','Smith')
,('Mary-Ann','Jenson')


Select Name
      ,Hits=count(*)
      ,Tables = count(distinct Src)
 From (
        Select Src='Table1',Name=concat(FirstName,LastName) From @Table1
        Union All
        Select Src='Table2',Name=concat(ForeName,SurName) From @Table2
     ) A
 Group By Name
 Having count(*)>1

<强>返回

Name        Hits    Tables
JohnSmith   2       2
相关问题