将同一张表出来的两部分内容再合成一张表

 --业务单成功率(eg:办公的成功的/办公的全部的)
  select t1.[ci_designerid],t2.[ci_designerid],t3.u_id,
  t1.办公成功的单子数 bgc,t2.办公全部的单子数 bgq,
  t1.餐饮成功的单子数 cyc,t2.餐饮全部的单子数 cgq, 
  t1.商业成功的单子数 syc,t2.商业全部的单子数 syq, 
  t1.酒店成功的单子数 jdc,t2.酒店全部的单子数 jdq, 
  t1.其他成功的单子数 qtc,t2.其他全部的单子数 qtq
  from
  --本表得到个人的各类的成功数
  --ci_leixing是单子的类型,ci_state是单子的状态,
  --ci_xiaozuid是小组的id,[ci_designerid]是用户id
 (SELECT [ci_designerid],  
  sum(case when ci_leixing=1 then 1 else 0 end) 办公成功的单子数,
  sum(case when ci_leixing=2 then 1 else 0 end) 餐饮成功的单子数,
  sum(case when ci_leixing=3 then 1 else 0 end) 商业成功的单子数,
  sum(case when ci_leixing=4 then 1 else 0 end) 酒店成功的单子数,
  sum(case when ci_leixing=5 then 1 else 0 end) 其他成功的单子数  
  FROM [DB_zab].[dbo].[zab_clientInfo]  
  where ci_state=7 and ci_xiaozuid=21 and ci_timeJd>'2012-05-20' and ci_timejd<'2013-09-09' 
  and ([ci_designerid] in (select u_id from zab_userlist where u_zuhao=1)) 
  group by [ci_designerid]) t1
  left join 
  --右连接,本表得到个人的各类的总数
  (SELECT  [ci_designerid],  
  sum(case when ci_leixing=1 then 1 else 0 end) 办公全部的单子数,
  sum(case when ci_leixing=2 then 1 else 0 end) 餐饮全部的单子数,
  sum(case when ci_leixing=3 then 1 else 0 end) 商业全部的单子数,
  sum(case when ci_leixing=4 then 1 else 0 end) 酒店全部的单子数,
  sum(case when ci_leixing=5 then 1 else 0 end) 其他全部的单子数  
  FROM [DB_zab].[dbo].[zab_clientInfo]  
  where ci_xiaozuid=21 and ci_timeJd>'2012-05-20' and ci_timejd<'2013-09-09' 
  and ([ci_designerid] in (select u_id from zab_userlist where u_zuhao=1))  
  group by [ci_designerid]) t2
  on
  t1.[ci_designerid]=t2.[ci_designerid]
  right join 
  --左链接根据小组id得到小用员工信息
  (select * from zab_userlist where u_zuhao=1) t3
  on t1.ci_designerid=t3.u_id

这样可以把没有数据的员工也显示出来

结合绑定出来结果

原文地址:https://www.cnblogs.com/tianrui/p/3316587.html