关于SQL的一个问题,求解,急,万分感谢
两张表:表A、B,两张表中:
A表字段:Id,PersonName,PersonId;
B表字段:Id,AId,IsFinish(AId为A表中的主键),
现在要查询A表与B表关联的数据中,A的PersonName,PersonId,以及他们出现的总个数以及IsFinish为”0“的个数和IsFinish为”1“的分别个数。
如下:
select a.PersonId ,a.PersonName,COUNT(*) as PersonCount from A a
left join B b on b.AId=a.Id
where 1=1 and a.PersonId is not null
group by a.PersonId ,a.PersonName
现在这样是查询的PersonName、PersonId、他们的总条数,但是我现在不知道后面咋加上去B表中IsFinish条件为‘0’的个数和为‘1’的个数
本人开始时这么想的:
select a.PersonId ,a.PersonName,COUNT(*) as PersonCount ,
(select COUNT(*) from B b1 where b1 .Id=b.Id and (b.IsFinish ='1' )) as FinishCount,
(select COUNT(*) from B b1 where b1 .Id=b.Id and (b.IsFinish ='0' )) as NoFinishCount,
from A a
left join B b on b.AId=a.Id
where 1=1 and a.PersonId is not null
group by a.PersonId ,a.PersonName
但是这样直接语法就错误了group by里面加进去IsFinish 就不是我想要的结果了,求知道的朋友能帮忙看下应该怎么写,万分感谢。
------解决方案--------------------select z1.contsub, geshu3, geshu4, geshu5
from (select s1.contsub, count(s1.contsub) as geshu3
from sup_contmain s1
left join sup_contgdzj s2 on s2.contno = s1.contsub
group by s1.contsub) z1
left join (select s6.contsub, count(s6.contsub) as geshu4
from sup_contmain s6
left join sup_contgdzj s7 on s7.contno = s6.contsub
where s7.str1 = '1'
group by s6.contsub) z2 on z1.contsub = z2.contsub
left join (
select s8.contsub, count(s8.contsub) as geshu5
from sup_contmain s8
left join sup_contgdzj s9 on s9.contno = s8.contsub
where s9.str1 = '2'
group by s8.contsub) z3 on z1.contsub = z3.contsub
------解决方案--------------------sum(case when b.IsFinish = 0 then 1 else 0 end) as col1,
sum(case when b.IsFinish = 1 then 1 else 0 end) as col