增强一下功能 给出姓名出现次数的同时 给出在哪些表中出现
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