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)


  • 2021-01-06 23:09:38

    mp3解码器转PCM合并

    首先,为了混合两个音频文件,您需要操纵它们的原始表示;由于MP3文件被压缩,您无法直接访问信号的原始表示.您需要对压缩的MP3流进行解码,以便“理解”您的音频信号的波形,然后可以混合使用.

  • 2021-01-08 16:47:37

    nodejs如何使用fetch

    node 中没有实现 fetch,你可以使用 node-fetch,使得在 node 中也可以使用 fetch.

  • 2021-01-08 16:49:59

    CommonJs 与 ESModule区别

    node中模块导入require是一个内置的函数,因此只有在运行后我们才可以得知模块导出内容,无法做静态分析

  • 2021-01-08 16:54:08

    如何在 Node.js 中使用 import / export 的三种方法

    注:第1、2种方法均是借助 babel,需要注意的是文章使用的babel版本 < 7。从 babel 7.X 版本开始,部分包名、用法发生了些许变化,大体与7之前的用法类似,详细请到官方手册学习 7.X 版本的改动(Babel 踩坑总结(三) —— 7.X 版本升级是我对 7.X 版本三大改动的总结)