mysql xml integer_MySQL分段统计SQL写法 与 Mybatis 报错:java.math.BigDecimal cannot be cast to java.lang.Inte...

标签:

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‘

-> fromstudent_course->;+------+-------+-------+-------+------+

| <60 | 60~69 | 70~79 | 80~89 | >=90 |

+------+-------+-------+-------+------+

| 2 | 1 | 1 | 1 | 10 |

+------+-------+-------+-------+------+

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

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

mapper接口:

Map getScoreStatistics();

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

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

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

正确的处理方法是,返回 Map,然后

{"<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 getScoreStatistics();

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

Map getScoreStatistics();

Map resultMap = this.studentCourseMapper.getScoreStatistics();

int 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 1 else 0 end)

标签:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值