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-03-11 09:43:20

    JavaScript shift() 方法

    shift() 方法用于把数组的第一个元素从其中删除,并返回第一个元素的值。

  • 2020-03-11 09:45:19

    45个优秀的vue开源项目

    在过去一年里,前端开发发展迅速,前端工程师的薪资亦是水涨船高。2019 更是热度不减,而作为近年来尤为热门的前端框架,Vue.js 自是积累了大量关注。本文将为你介绍 2019 年最值得关注的 45 个 Vue.js 开源项目——Let's go!

  • 2020-03-11 18:26:52

    Mac设置ADB

    adb在 ~/Library/Android/sdk/platform-tools文件夹内

  • 2020-03-11 19:40:56

    java.util.zip.ZipException: zip file is empty

    三、总结 出现 java.util.zip.ZipException: zip file is empty错误,表示你本地使用的jar包或者aar包可能为空,你可以检查下文件大小,如果为空,可以替换本地的jar包或者aar包为正常的jar包或者aar包,或者如果官方有相关的资源的话直接使用官方的依赖资源即可。

  • 2020-03-11 21:22:36

    Vue的组件化之notification组件/Vue.extend()

    一、把组件的内部结构写好,写成一个vue文件notification.vue。 二、全局设置组件属性。//如果后面不需要直接引入组件的方式调用,可以不用全局注册 index.js中一般写的是需要全局设置的属性。