日期:2014-05-18  浏览次数:20403 次

求一合并SQL语句
SQL code

select twoqudao as 名称,count(Invoice)as 单数1 from Customer_Service  
where twoqudao like '%%' and
twoqudao<>'汇展' and
twoqudao<>'非训' and
twoqudao<>'泥煤' and
sjfddate is null  and
kehuqianshoudate is null or
kehuqianshoudate=''  
group by twoqudao
--得出如下结果
/*姓名    单数1
张三    2
李思    2
王二    1
*/
select twoqudao as 名称,count(Invoice)as 单数2 from Customer_Service
where twoqudao like '%%' and
twoqudao<>'汇展' and
twoqudao<>'非训' and 
twoqudao<>'泥煤' and 
sjfddate is null or 
sjfddate='' 
group by twoqudao
--得出如下结果
/*姓名    单数2
张三    3
李思    2
王二    8
三五    9
*/

--最终想要的结果
/*姓名    单数1    单数2
张三    2    3
李思    2    2
王二    1    8
三五    Null    9
*/




------解决方案--------------------
SQL code

select twoqudao as 名称,count(Invoice)as 单数1 from Customer_Service  
where twoqudao like '%%' and
twoqudao<>'汇展' and
twoqudao<>'非训' and
twoqudao<>'泥煤' and
sjfddate is null  and
(isnull(kehuqianshoudate,'')='' or isnull(sjfddate,'')='')
group by twoqudao

------解决方案--------------------
SQL code
select
  a.*,b.单数2
from
(
select twoqudao as 名称,count(Invoice)as 单数1 from Customer_Service  
where twoqudao like '%%' and
twoqudao<>'汇展' and
twoqudao<>'非训' and
twoqudao<>'泥煤' and
sjfddate is null  and
kehuqianshoudate is null or
kehuqianshoudate=''  
group by twoqudao
)a
left join
(
select twoqudao as 名称,count(Invoice)as 单数2 from Customer_Service
where twoqudao like '%%' and
twoqudao<>'汇展' and
twoqudao<>'非训' and 
twoqudao<>'泥煤' and 
sjfddate is null or 
sjfddate='' 
group by twoqudao
)b
on
 a.名称=b.名称