Group By Count不能显示0的问题

问题:

  如对表:

/*====================================================
  id              |score              |grade
  ---------------------------------------------------
  1                |0                  |1
  2                |4                  |1
  3                |6                  |2
  4                |1                  |2
  5                |7                  |3
  6                |3                  |3
  ====================================================*/

   希望统计各grade中score>5的数量

  如果用如下语句:

1 select grade,count(*) from tmpTable where score>5 group by grade

  则不能得到grade==1的结果,但实际是期望得到0的

分析:

  造成这一现象的原因是, score<=5的情况都被首先剔除了,无法被group by

解决:

  使用如下语句查询:

select a.grade,ifnull(count(*),0)
    fromselect * from tmpTable group by grade) a
            left join
            ( select grade,count(*) from tmpTable where score>5 group by grade) b
            on a.grade=b.grade

  原理:

    借助另一个所期待行存在的“表”,通过左联,将期望的行select出来,再借助ifnull函数进行替换 以实现显示0

    注意:不同数据库实现ifnull功能可能采用不同的函数,如NVL等。本例使用的数据库是sqlite,其他数据库未测试

posted on 2016-03-28 22:28  编号2784  阅读(1488)  评论(0编辑  收藏  举报

导航