表 a  id   name   m     price 1     a     11     10
 2     b     12     14
 3     c     13     20
表 b id    m    cp
 1     11   12
 2     11    0
 3     11   22
 4     11   0
 5     11   12
 6     12    12
 7     12    8
 8     12    0
 9     12    1
10     13    1
11     13    33
12     13    0
13     13    0希望统计出表 b的 cp值 大于0 的数量得出的结果如下表a.name  cp>0的数量
a  3
b  2
c  2求 sql 语句

解决方案 »

  1.   

    select a.name,count(*)
    from a inner join b on a.m=b.m
    where b.cp>0
    group by a.name
      

  2.   

    select 
      a.name,
      count(1) as cpcount
    from a
    join b on a.m=b.m and b.cp>0
    group by a.name
      

  3.   

    假如 再多一列, 要求也统计 =0的数列呢?就是要求得到的结果是
    name >0  =0
    a    3   2
    b    2   1
    c    2   2
      

  4.   


    select group by a.name,
    sum(if(b.cp>0,1,0)),
    sum(if(b.cp=0,1,0))
    from a inner join b on a.m=b.m
    group by a.name 建议提问时一次说清楚。问题说明越详细,回答也会越准确!参见如何提问。(提问的智慧
      

  5.   

    select 
      a.name,
      sum(case when b.cp>0 then 1 else 0 end) as `>0`,
      sum(case when b.cp=0 then 1 else 0 end) as '=0'
    from a
    join b on a.m=b.m   
    group by a.name
      

  6.   

    select 
      a.name,
      sum(case when b.cp>0 then 1 else 0 end) as `>0`,
      sum(case when b.cp=0 then 1 else 0 end) as `=0`
    from a
    join b on a.m=b.m   
    group by a.name