MySQL分段统计SQL写法 与 Mybatis 异常 java.math.BigDecimal cannot be cast to java.lang.Integer

2017-11-19 00:16:58
mysql> select
    -> sum(case when score<60 then 1 else 0 end) as '<60',    -> sum(case when score>=60 and score<=69 then 1 else 0 end) as '60~69',    -> sum(case when score>=70 and score<=79 then 1 else 0 end) as '70~79',    -> sum(case when score>=80 and score<=89 then 1 else 0 end) as '80~89',    -> sum(case when score>-90 then 1 else 0 end) as '>=90'
    -> from student_course    -> ;+------+-------+-------+-------+------+| <60  | 60~69 | 70~79 | 80~89 | >=90 |+------+-------+-------+-------+------+|    2 |     1 |     1 |     1 |   10 |+------+-------+-------+-------+------+

复制代码

 采用mybatis时,xml文件配置如下处理:

复制代码

  <select id="getScoreStatistics" resultType="map">
      select 
        sum(case when score &lt; 60 then 1 else 0 end) as '&lt;60',
        sum(case when score &gt;= 60 and score &lt;= 69 then 1 else 0 end) as '60~69',
        sum(case when score &gt;= 70 and score &lt;= 79 then 1 else 0 end) as '70~79',
        sum(case when score &gt;= 80 and score &lt;= 89 then 1 else 0 end) as '80~89',
        sum(case when score &gt;= 90 then 1 else 0 end) as '&gt;=90'
    from student_course  </select>

复制代码

mapper接口:

Map<String, Object> getScoreStatistics();

注意,这里如果使用 Map<String, Integer> 作为返回值,会报错:

java.math.BigDecimal cannot be cast to java.lang.Integer

原因是,sum() 的结果是作为 java.math.BigDecimal 来处理的, 而他不能直接转换成 java.lang.Integer,所以报错。

正确的处理方法是,返回 Map<String, Object>,然后

{"<60":2,"60~69":1,"70~79":1,"80~89":1,">=90":5}

int count1 = Integer.parseInt(resultMap.get("<60").toString());

通过Object类型的 toString()方法,然后 Integer.parseInt() 这里才能得到正确的结果。

当然我们也可以直接返回:Map<String, BigDecimal> getScoreStatistics();

然后通过BigDecimal.intValue() 来获得我们需要的值:

    Map<String, BigDecimal> getScoreStatistics();
 count = resultMap.get("<60").intValue();

 总结

1)sql中的 sum() 返回返回值在mybatis中是作为BigDecimal来返回的,所以我们有两种方法来处理:

   1> 返回 Object 值,然后通过 Integer.parseInt(obj.toString()); 来得到int值;

   2> 返回 BigDecimal 值,然后通过 BigDecimal.intValue()得到需要的值,应该说我们推荐使用第二种方法。

2)mysql分段统计方法:sum(case when score<60 then else end)


  • 2020-12-12 17:43:33

    linux docker部署gitlab-ce

    首先需要从docker镜像仓库当中获取gitlab-ce的最新镜像文件,由于我本机已经获取了该镜像,所以在此获取的时候会给如下提示。

  • 2020-12-13 19:44:07

    运行中的docker实例添加-v挂载文件夹

    之前有人问我Docker容器启动之后还能否再挂载卷,考虑到mnt命名空间的工作原理,我一开始认为这很难实现。不过现在Petazzoni通过使用nsenter和绑定挂载实现了这个需求,你可以在你的环境中测试下。

  • 2020-12-13 19:49:32

    Docker run命令详解

    命令格式:docker run [OPTIONS] IMAGE [COMMAND] [ARG...] Usage: Run a command in a new container 中文意思为:通过run命令创建一个新的容器(container)

  • 2020-12-13 20:15:43

    解决gitlab限制上传文件大小的问题

    服务端的限制有两个地方一个是gitlab本身,另外一个是gitlab使用的nginx。 gitlab本身也是很好解决的,使用管理员用户登录gitlab在设置Account and limit中加大Maximum attachment size (MB)和Maximum push size (MB)即可解决 nginx的话修改gitlab.rb这个文件中

  • 2020-12-14 15:06:50

    youtube-dl视频下载神器

    youtube-dl 是一款命令行下的视频下载工具,看着名称像是 YouTube 下载工具,其实这款工具不仅支持 YouTube ,还支持非常多的视频网站,比如优酷、爱奇艺、 bilibili 等,在写这篇日志的时候,暂时不支持腾讯视频。