Mysql> Select - sum( Case whenScore< - Then 1 Else 0 End) as '<60', - sum( Case whenScore>= - andScore<= the Then 1 Else 0 End) as '60~69', - sum( Case whenScore>= - andScore<= - Then 1 Else 0 End) as '70~79', - sum( Case whenScore>= the andScore<= the Then 1 Else 0 End) as '80~89', - sum( Case whenScore>- - Then 1 Else 0 End) as '>=90' - fromStudent_course - ;+------+-------+-------+-------+------+| < - | -~ the | -~ - | the~ the | >= - |+------+-------+-------+-------+------+| 2 | 1 | 1 | 1 | Ten |+------+-------+-------+-------+------+
With MyBatis, the XML file is configured as follows:
<SelectID= "Getscorestatistics"Resulttype= "Map">Select sum ( case when score<1 Else 0 end) as '<sum ( case when score>= Score<= 1 Else 0 end) as ' 60~69 ', sum ( case when score>= Score and<= 1 Else 0 end) as ' 70~79 ', sum ( case when score>= Score<= 1 Else 0 end) as ' 80~89 ', sum ( case when score>= 1 Else 0 end) as '>=90 ' from Student_course</Select>
Mapper Interface:
Map<string, object> getscorestatistics ();
Note that if you use Map<string, integer> as the return value, you will get an error:
Java.math.BigDecimal cannot is cast to Java.lang.Integer
The reason is that the result of sum () is handled as Java.math.BigDecimal, and he cannot be converted directly to Java.lang.Integer, so the error is.
The correct approach is to return map<string, Object>
{"<60": 2, "60~69": 1, "70~79": 1, "80~89": 1, ">=90": 5}
int count1 = Integer.parseint (Resultmap.get ("<60"). toString ());
You can get the correct result by using the toString () method of type object and then Integer.parseint ().
Of course we can also directly return: Map<string, bigdecimal> getscorestatistics ();
Then get the values we need by Bigdecimal.intvalue ():
Map<string, bigdecimal> getscorestatistics ();
map<string, bigdecimal> resultmap = This.studentCourseMapper.getScoreStatistics ();
int count = Resultmap.get ("<60"). Intvalue ();
Summary :
1) the sum () in SQL returns the return value returned as BigDecimal in MyBatis, so we have two ways to handle it:
1> Returns an Object value and then Integer.parseint (obj.tostring ()) to get the int value;
2> Returns the BigDecimal value and then obtains the desired value through Bigdecimal.intvalue () , it should be said that we recommend using the second method.
2) MySQL Segmentation statistics method:sum (case when score< 1 Else 0 end)
MySQL segmentation statistics SQL notation and Mybatis error: Java.math.BigDecimal cannot be cast to Java.lang.Integer