日期:2014-05-17  浏览次数:20538 次

SQL查询结果连接的问题!!!!!
select * from
(select CustomerName,c.CustomerID,count(*) as Boys
from tb_masEmPersonalInfo b join tb_masEmployeeEmployer a 
on b.EmpersonalInfoID=a.EmpersonalInfoID
join tb_masCustomer c on a.CustomerID=c.CustomerID
where b.GenderID=1 and a.EwStatus in ('A','N')
group by c.CustomerName,c.CustomerID) Boys

查询结果的列为 CustomerName,CustomerID,Boys

select *from
(select CustomerName,c.CustomerID,count(*) as Girls
from tb_masEmPersonalInfo b join tb_masEmployeeEmployer a
on b.EmPersonalInfoID=a.EmPersonalInfoID
join tb_masCustomer c on a.CustomerID=c.CustomerID
where b.GenderID=2 and a.EwStatus in ('A','N')
group by CustomerName,c.CustomerID) Girls

查询结果的列为 CustomerName,CustomerID,Girls


这两个查询结果连接在一张表里.需要实现的结果为

查询结果的列为 CustomerName,CustomerID,Boys,Girls

------解决方案--------------------
SQL code
select CustomerName,c.CustomerID
,Sum(case when b.GenderID=1 then 1 else 0 end) as Boys
,Sum(case when b.GenderID=2 then 1 else 0 end) as Boys
from tb_masEmPersonalInfo b join tb_masEmployeeEmployer a  
on b.EmpersonalInfoID=a.EmpersonalInfoID
join tb_masCustomer c on a.CustomerID=c.CustomerID
where  a.EwStatus in ('A','N')
group by c.CustomerName,c.CustomerID

------解决方案--------------------
SQL code
select * from
(select CustomerName,c.CustomerID,sum(case when b.GenderID=1  then 1 else 0 end ) as Boys,sum(case when b.GenderID=2 then 1 else 0 end ) as Girls,
from tb_masEmPersonalInfo b join tb_masEmployeeEmployer a  
on b.EmpersonalInfoID=a.EmpersonalInfoID
join tb_masCustomer c on a.CustomerID=c.CustomerID
where a.EwStatus in ('A','N')
group by c.CustomerName,c.CustomerID)