create table #文书表1(id int,年度 varchar(30), 科室 varchar(30), 企业名称 varchar(30), 企业地址 varchar(30)) create table #文书表2(id int,年度 varchar(30), 科室 varchar(30), 企业名称 varchar(30), 文书编号 varchar(30)) create table #文书表3(id int,年度 varchar(30), 科室 varchar(30), 企业名称 varchar(30), 法人代表 varchar(30))insert into #文书表1(ID,年度, 科室, 企业名称,企业地址) values(1,'2010','科室1', '企业1','地址') insert into #文书表1(ID,年度, 科室, 企业名称,企业地址) values(2,'2010','科室1', '企业1','地址') insert into #文书表1(ID,年度, 科室, 企业名称,企业地址) values(3,'2011','科室1', '企业1','地址')insert into #文书表2(ID,年度, 科室, 企业名称,文书编号) values(1,'2010','科室1', '企业1','001') insert into #文书表2(ID,年度, 科室, 企业名称,文书编号) values(2,'2010','科室2', '企业2','002') insert into #文书表2(ID,年度, 科室, 企业名称,文书编号) values(3,'2011','科室1', '企业1','003')insert into #文书表3(ID,年度, 科室, 企业名称,法人代表) values(1,'2010','科室1', '企业1','张') insert into #文书表3(ID,年度, 科室, 企业名称,法人代表) values(2,'2010','科室1', '企业2','李') insert into #文书表3(ID,年度, 科室, 企业名称,法人代表) values(3,'2011','科室1', '企业1','陈')select 年度, 科室, 企业名称,sum(case t when '文书表1' then 1 else 0 end) as 文书表1, sum(case t when '文书表2' then 1 else 0 end) as 文书表2,sum(case t when '文书表3' then 1 else 0 end) as 文书表3 from ( select ID,年度, 科室, 企业名称,'文书表1' as t from #文书表1 union select ID,年度, 科室, 企业名称,'文书表2' as t from #文书表2 union select ID,年度, 科室, 企业名称,'文书表3' as t from #文书表3 ) b group by 年度, 科室, 企业名称drop table #文书表1 drop table #文书表2 drop table #文书表3
create table #文书表2(id int,年度 varchar(30), 科室 varchar(30), 企业名称 varchar(30), 文书编号 varchar(30))
create table #文书表3(id int,年度 varchar(30), 科室 varchar(30), 企业名称 varchar(30), 法人代表 varchar(30))insert into #文书表1(ID,年度, 科室, 企业名称,企业地址) values(1,'2010','科室1', '企业1','地址')
insert into #文书表1(ID,年度, 科室, 企业名称,企业地址) values(2,'2010','科室1', '企业1','地址')
insert into #文书表1(ID,年度, 科室, 企业名称,企业地址) values(3,'2011','科室1', '企业1','地址')insert into #文书表2(ID,年度, 科室, 企业名称,文书编号) values(1,'2010','科室1', '企业1','001')
insert into #文书表2(ID,年度, 科室, 企业名称,文书编号) values(2,'2010','科室2', '企业2','002')
insert into #文书表2(ID,年度, 科室, 企业名称,文书编号) values(3,'2011','科室1', '企业1','003')insert into #文书表3(ID,年度, 科室, 企业名称,法人代表) values(1,'2010','科室1', '企业1','张')
insert into #文书表3(ID,年度, 科室, 企业名称,法人代表) values(2,'2010','科室1', '企业2','李')
insert into #文书表3(ID,年度, 科室, 企业名称,法人代表) values(3,'2011','科室1', '企业1','陈')select 年度, 科室, 企业名称,sum(case t when '文书表1' then 1 else 0 end) as 文书表1, sum(case t when '文书表2' then 1 else 0 end) as 文书表2,sum(case t when '文书表3' then 1 else 0 end) as 文书表3
from
(
select ID,年度, 科室, 企业名称,'文书表1' as t from #文书表1
union
select ID,年度, 科室, 企业名称,'文书表2' as t from #文书表2
union
select ID,年度, 科室, 企业名称,'文书表3' as t from #文书表3
) b group by 年度, 科室, 企业名称drop table #文书表1
drop table #文书表2
drop table #文书表3