zoukankan      html  css  js  c++  java
  • 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,其他数据库未测试

  • 相关阅读:
    java抽象类
    java不支持多继承
    logback颜色
    @ConfigurationProperties、@Value、@PropertySource
    redis命令
    mac下安装rabbitmq
    mac下安装jmeter
    python TypeError: 'int' object is not callable 问题解决
    白炽灯串联发光问题_高中知识(原创)
    python 离散序列 样本数伸缩(原创)
  • 原文地址:https://www.cnblogs.com/dusmos/p/5330974.html
Copyright © 2011-2022 走看看