我有一个包含6个表的SQL Server数据库。
在这些表格中有一种客户名称。
我要做的是计算多少次:
在SQL中有一种简单的方法可以做这种类型的事情吗?
由于
答案 0 :(得分:1)
我想你想要一个union all
和group 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