有三个表:table1  --人员表
========================
RenID int   //人员ID
Gsid  int   //公司ID
Bmid  int   //部门ID
table2  --考试范围表,记录某项考试的范围包括哪些公司部门
=====================
KsID  int   //考试ID号
GsID  int   //公司ID
BmID  int   //部门ID
table3  --考试记录表,记录已参加考试人员的记录,未参加的没有记录
=====================
Ksid  int   //考试ID号
RenID int   //人员ID号
我想通过一条SQL语句实现的统计功能:统计某项考试中,各公司各部门有多少人参加了,有多少人未参加,形如:
Gsid  Bmid  Count1(参加人数)  Count2(未参加人数)
================================================
1       1     100                20
1       2     90                 8
2       1     800                229
2       9     89                 10
.........请高手指点,谢谢!

解决方案 »

  1.   

    select a.RenID,a.Bmid,count(b.Renid) as Count1,count(1)-count(b.Renid) as Count2 from tb1 a left join tb2 b
    on a.RenID=b.RenID
    group by a.RenID,a.Bmid
      

  2.   

    select a.RenID,a.Bmid,count(b.Renid) as Count1,count(1)-count(b.Renid) as Count2 from table1 a left join table3 b
    on a.RenID=b.RenID
    group by a.RenID,a.Bmid
      

  3.   

    select t1.gsid,t1.bmid,Count1=count(distinct t3.renid),Count2=count(distinct t1.renid)-count(distinct  t3.renid) from table1 t1 
    left join table2 t2 on t1.gsid=t2.gsid and t1.bmid=t2.bmid
    left join table3 t3 on t2.ksid=t3.ksid
    group by t1.gsid,t1.bmid
      

  4.   

    orselect t1.gsid,t1.bmid,
    Count1=count(t3.renid),
    Count2=count(t1.renid)-count(t3.renid) 
    from table1 t1 
    left join table2 t2 on t1.gsid=t2.gsid and t1.bmid=t2.bmid
    left join table3 t3 on t2.ksid=t3.ksid
    group by t1.gsid,t1.bmid
      

  5.   

    select t1.gsid,t1.bmid,Count1=count(distinct t3.renid),Count2=count(distinct t1.renid)-count(distinct  t3.renid) from table1 t1 
    inner join table2 t2 on t1.gsid=t2.gsid and t1.bmid=t2.bmid
    left join table3 t3 on t2.ksid=t3.ksid and t3.RenID=t1.RenID
    group by t1.gsid,t1.bmid