2017-08-15 114 views
-1

我有一个带有6个表的SQL Server数据库。跨多个表匹配值

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

  • 在表一:用的名字,姓
  • 在表二:名字,第二个名字
  • 在表三:姓,姓

等等等等横跨6张桌子。

我所试图做的就是有多少次的计数:

  • 全名(姓和名的CONCAT)对所有的表出现。
  • 全名(姓氏和名字的CONCAT)跨越5个表
  • 全名(姓氏和名字的CONCAT)出现出现跨越4个表 等等等等
  • 全名(初的CONCAT和姓氏)​​只出现在表1中

在SQL中有没有一种简单的方法来做这种类型的事?

谢谢

+0

无关你的具体问题,但如果你在表上执行其他查询,请注意当您连接列值(除非你选择它们)。该索引不能用于动态值。例如,这将使用索引(如果索引存在):'select * from table where first_name ='John'and last_name ='Doe'',while this will not use an index'select * from table where concat(first_name ,last_name)='JohnDoe')'。我只提到这个,因为你在你的问题中明确指出了“CONCAT”。 – RToyo

回答

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; 
+0

谢谢Gordon。努力完成这项工作。 我应该用表名替换** all ** t1,t2等吗? 只是为了测试它,我只是试图让它与表1(客户)和表2(CustSystem2)一起工作,但无法看到我出错的地方。 (Get'Invalid Object Name'errors!) – NewAtThis

+0

@NewAtThis。 。 。如果你喜欢,你可以在别名之前添加表名:'来自Customers t1','来自CustSystem2 t2',等等。你需要填写'。 。 .'与额外的桌子。 –

+0

认为我开始得到这个 - 只是! 已经创建了一个DBFiddle来尝试理解。 [链接](http://dbfiddle.uk/?rdbms=sqlserver_2016&fiddle=30310edeb1c0e14f946a82d4675ba037) – NewAtThis

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 
+0

谢谢约翰。 当将'Table1'更改为'Customers'的实际表名时,我只是得到无效的对象名称错误。 – NewAtThis

+0

@NewAtThis你是否同步每个表的字段名称。没有实际的表名和相关的字段名称,我只能提供一个插图.... fyi Src可以是任何不同的值,即1 - 6 –

+0

@NewAtThis这是一个关于http://dbfiddle.uk/的插图?rdbms = sqlserver_2016&fiddle = 9e80fc47d6bc49ca19a3725cb4cf3eb5只创建了两个表,但是证明了这个appoach的工作原理 –