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)


  • 2019-04-01 22:59:22

    Android Studio 3.0 利用cmake搭建jni环境(很详细哦)

    我用的Android Studio是3.0的版本,然后想搭建一下jni的环境。这里把自己遇到的问题和注意点都记录下。 首先是需要在android studio里面安装最基本的环境。 打开Default Preference里面查看SDK Tool选项。

  • 2019-04-01 23:20:58

    隐藏在图片中的密钥

    在客户端开发的时候,有时需要把密钥保存在本地。这时就会遇到密钥安全性的问题。要保证密钥安全性,无非就是混淆、隐藏、白盒等手段。本文以隐藏在图片中来阐述密钥的安全保存。

  • 2019-04-01 23:22:33

    验证数字签名

    应预先设置验证首选项。在打开 PDF 后显示包含签名的验证详细信息时,这有助于确保数字签名有效。有关详细信息,请参阅设置签名验证首选项。

  • 2019-04-01 23:23:27

    图像隐写之使用PHP隐藏图像中的文本

    隐写术是一门研究隐藏信息的科学艺术,通过隐写术,可以只让发送者和接收者知道隐藏的信息。 图像隐写术则是研究将数据隐藏在图像中,通过该技术可以防止无关用户发现这些隐藏的信息或数据。

  • 2019-04-08 16:01:57

    Window 设置pm2开机自启动服务

    下面用 pm2 来启动我们自己的服务程序 app.js, 然后告诉 pm2 开机后自动运行我 app.js 继续在管理员命令行下, cd 到 app.js 所在目录