想查询 姓名(其中的一个字段),
问题1,是:3个表中姓名字段都出现的姓名有那些。表1,姓名=表2,姓名=表3的姓名。
问题2,是查询,3个表中只要其中两个表中出现的相同的姓名。如,表1,姓名=表2,姓名或是表1,姓名=表3,姓名,或是表2,姓名=表3,姓名。
问题3,如果是不只3个表,而是可能4个,5个表呢?
先谢谢那位高手指点一下。
创造一个临时表
create table #Name
(
Name varchar(20)
)
Insert into #Name
select 姓名 from 表1
union all
Select 姓名 from 表2
....
union all
Select 姓名 from 表50
...
有1万零一个表就写1万个unin all
然后
Select 姓名= name, 相同次数 = count(*) from #Name group by name
然后前台代码来判断哪些出现2次 哪些出现3次,4次,5次的...
增强一下功能 给出姓名出现次数的同时 给出在哪些表中出现
drop table #Name
create table #Name
(
Name varchar(20),
tbl varchar(10)
)
Insert into #Name
select
'A','表4'
union all
select 'A','表5'
union all
select 'V','表1'
union all
select 'V','表2'
union all
select 'V','表5'
union all
select 'C','表6'
union all
select 'A','表7'
union all
select 'V','表8'
delete #name
drop table #1
create table #1
(
ID int identity(1,1),
Name varchar(100),
cnt int,
tbl varchar(10),
MaxID int,
MinID int
)
insert into #1
select a.Name,b.cnt,a.tbl,0,0 from #name a join (
select Name, count(*) as cnt from #name group by name) b
on a.name = b.name
update #1 set MaxID = b.MaxID from #1 a
join (select Name, Max(ID) as MaxID from #1 group by Name) b
on a.name = b.name
update #1 set MinID = b.MinID from #1 a
join (select Name, Min(ID) as MinID from #1 group by Name) b
on a.name = b.name
select * from #1 where ID <> MaxID and cnt<>1
while @@RowCount <> 0
begin
Update #1 set tbl = a.tbl+','+b.tbl from #1 a join (select * from #1) b
on a.Name = b.Name and a.ID = a.MinID and b.ID = b.MaxID
and a.cnt <>1
delete #1 where ID = MaxID and MaxID <> MinID
update #1 set MaxID = b.MaxID from #1 a
join (select Name, Max(ID) as MaxID from #1 group by Name) b
on a.name = b.name
update #1 set MinID = b.MinID from #1 a
join (select Name, Min(ID) as MinID from #1 group by Name) b
on a.name = b.name
select * from #1 where ID <> MaxID and cnt <>1
end
select 姓名 ='Name', 出现次数 = cnt,出现在哪些表中 = tbl from #1