select a.*,bb.拜访工单数 ,isnull(分配单位已拜访数,0)'分配单位已拜访数' ,isnull(其他单位拜访数,0)'其他单位拜访数' from (select 客户代表 , count(1)'应拜访数' from #a group by 客户代表) a left join (select 客户代表,count(*)'分配单位已拜访数' from (select 客户代表,单位名称 from #a intersect (select 拜访人, 拜访单位名称 from #b)) a group by 客户代表 ) c on a.客户代表=c.客户代表 left join (select 拜访人 ,count(*)'拜访工单数' from #b group by 拜访人 ) bb on a.客户代表=bb.拜访人 left join (select 拜访人 ,count(*)'其他单位拜访数' from (select 拜访人, 拜访单位名称 from #b except (select 客户代表,单位名称 from #a) ) a group by 拜访人) dd on a.客户代表=dd.拜访人
) cte 把这个写在外面就好啦,
呵呵,非常感谢2位,SQL2000好象也不支持intersect语句。
select *, 应拜访数-分配单位已拜访数 '分配单位未拜访数' from(select a.*,bb.拜访工单数 ,isnull(分配单位已拜访数,0)'分配单位已拜访数' ,isnull(其他单位拜访数,0)'其他单位拜访数' from (select 客户代表 , count(1)'应拜访数' from #a group by 客户代表) a left join ( select 客户代表,count(*)'分配单位已拜访数' from #a a where exists(select * from #b where 拜访人=a.客户代表 and 拜访单位名称=a.单位名称) group by 客户代表 ) c on a.客户代表=c.客户代表 left join (select 拜访人 ,count(*)'拜访工单数' from #b group by 拜访人 ) bb on a.客户代表=bb.拜访人 left join ( select 拜访人 ,count(*)'其他单位拜访数' from #b b where not exists(select * from #a where 客户代表=b.拜访人 and 单位名称=b.拜访单位名称) group by 拜访人) dd on a.客户代表=dd.拜访人) cte已经改过来了, 这样SQL 2000应该能用
select *, 应拜访数-分配单位已拜访数 '分配单位未拜访数' from(
select a.*,bb.拜访工单数 ,isnull(分配单位已拜访数,0)'分配单位已拜访数' ,isnull(其他单位拜访数,0)'其他单位拜访数' from
(select 客户代表 , count(1)'应拜访数' from #a group by 客户代表) a
left join (select 客户代表,count(*)'分配单位已拜访数' from (select 客户代表,单位名称 from #a intersect (select 拜访人, 拜访单位名称 from #b)) a group by 客户代表 ) c
on a.客户代表=c.客户代表
left join (select 拜访人 ,count(*)'拜访工单数' from #b group by 拜访人 ) bb on a.客户代表=bb.拜访人
left join (select 拜访人 ,count(*)'其他单位拜访数' from (select 拜访人, 拜访单位名称 from #b except (select 客户代表,单位名称 from #a) ) a group by 拜访人) dd
on a.客户代表=dd.拜访人
)
cte 把这个写在外面就好啦,
select *, 应拜访数-分配单位已拜访数 '分配单位未拜访数' from(select a.*,bb.拜访工单数 ,isnull(分配单位已拜访数,0)'分配单位已拜访数' ,isnull(其他单位拜访数,0)'其他单位拜访数' from
(select 客户代表 , count(1)'应拜访数' from #a group by 客户代表) a
left join ( select 客户代表,count(*)'分配单位已拜访数' from #a a where exists(select * from #b where 拜访人=a.客户代表 and 拜访单位名称=a.单位名称) group by 客户代表 ) c
on a.客户代表=c.客户代表
left join (select 拜访人 ,count(*)'拜访工单数' from #b group by 拜访人 ) bb on a.客户代表=bb.拜访人
left join ( select 拜访人 ,count(*)'其他单位拜访数' from #b b where not exists(select * from #a where 客户代表=b.拜访人 and 单位名称=b.拜访单位名称) group by 拜访人) dd
on a.客户代表=dd.拜访人) cte已经改过来了, 这样SQL 2000应该能用