框架:SpringBoot,Mybatis;数据库:MySQL
表中设计2个状态字段,每个字段有3种状态,统计这6个状态各自的数量
sql查询语句及结果如图
SQL:
SELECT
SUM(CASE WHEN A=0 THEN 1 ELSE 0 END) AS 'A0',
SUM(CASE WHEN A=1 THEN 1 ELSE 0 END) AS 'A1',
SUM(CASE WHEN A=2 THEN 1 ELSE 0 END) AS 'A2',
SUM(CASE WHEN B=0 THEN 1 ELSE 0 END) AS 'B0',
SUM(CASE WHEN B=1 THEN 1 ELSE 0 END) AS 'B1',
SUM(CASE WHEN B=2 THEN 1 ELSE 0 END) AS 'B2'
FROM test
效果达到了,接下来就是在项目中实际使用
以下仅设计为最简单的使用方式,有具体需求按需求增加逻辑
Controller:
@GettMapping("/findStatusCount")
public List<Object> findStatusCount(){
return statusCountService.findStatusCount();
}
Service:
List<Object> findStatusCount();
Service实现类:
@Override
public List<Object> findStatusCount() {
return statusCountMapper.selectStatusCount();
}
Mapper:
List<Object> selectStatusCount();
在自定义sql的xml中代码如下。
where中按需求加条件,resultType中使用HashMap时,可能展示时的顺序与查询结果顺序不同,因此使用LinkedHashMap
<select id="selectStatusCount" resultType="java.util.LinkedHashMap">
select
SUM(CASE WHEN A=0 THEN 1 ELSE 0 END) AS 'A0',
SUM(CASE WHEN A=1 THEN 1 ELSE 0 END) AS 'A1',
SUM(CASE WHEN A=2 THEN 1 ELSE 0 END) AS 'A2',
SUM(CASE WHEN B=0 THEN 1 ELSE 0 END) AS 'B0',
SUM(CASE WHEN B=1 THEN 1 ELSE 0 END) AS 'B1',
SUM(CASE WHEN B=2 THEN 1 ELSE 0 END) AS 'B2'
FROM test
<where>……</where>
</select>
结束~