两个表 a 和 b ,一对多的关系,即 a 表中存的为各个单位的基本信息, b 表存的是 各个单位对应的人员信息,b 表中的人员信息有个status 状态,现在我如何建立视图筛选出 a表中的所有单位的基本信息,此外再加上各个单位对应b表中各个status状态的人员数量。
如:a 表
          id        name       aa      bb    cc
          001       单位一     a1      b1    c1
          002       单位二     a2      b2    c2
         。
     b 表          id     unitid  unitname   aaaa      bbbb      status
          1        001   单位一     11        22          0
          2        001   单位一     22        11          0
          3        001   单位一     33        44          1
          4        002   单位二     55        44          0
          5        002   单位二     44        55          1
          
  
    希望的筛选结果:         id     name     aa     bb    cc  stauts0   status1
         001    单位一    a1     b1   c1     2          1
         002    单位二    a2     b2   c2     1          1
          
  在线等 

解决方案 »

  1.   

    select *,stauts0=(select count(*) from b where a.id=unitid and status=0),
             stauts1=(select count(*) from b where a.id=unitid and status=1)
    from a
      

  2.   

    select col... case when status = 0 then count(*) end,
    case when status = 1 then count(*) end
    from tb group by col...--分组查询
      

  3.   

    select a.* ,
    sum(case b.status  when 0 then 1 else 0 end) as status0,
    sum(case b.status  when 1 then 1 else 0 end) as status1
    from a  left join b  on a.id=b.unitid