查询结果如图所示:
返回的数据类型是Map<String ,Integer>类型
后端代码如下:
/**
* 统计各年龄阶段人员
* @return
*/
@Override
public Map<String, Integer> countPersonByAge() {
//用list集合接收查询出来的数据
List<Map<String, String>> ageList = this.baseMapper.countPersonByAge();
//用LinkedHashMapMap集合来保证集合的有序
Map<String, Integer> ageMap = new LinkedHashMap<>();
//用来存储所有年龄阶段
List<String> ageInfoList = new ArrayList<>();
ageInfoList.add("16");
ageInfoList.add("16-18");
ageInfoList.add("18-55");
ageInfoList.add("56-60");
ageInfoList.add("61");
Map<String, String> exisetMap = new HashMap<>();
//new一个HashMap来放入数据库查出来的年龄阶段和数量
for (Map<String, String> countListMap : ageList) {
//用
exisetMap.put(countListMap.get("age"), countListMap.get("count"));
}
for (String ageInfo : ageInfoList) {
//通过key取出value,通过age取出count
Integer count = Convert.toInt(exisetMap.get(ageInfo), 0);
//如果年龄段查询出来的数据为空,给默认值0
if (count == null) {
count = 0;
}
ageMap.put(ageInfo, count);
}
return ageMap;
}
sql:
SELECT
age,
count( * ) AS count
FROM
(
SELECT
CASE
WHEN age <![CDATA[ <= ]]> 16 THEN '16'
WHEN age <![CDATA[ <= ]]> 18 AND age >= 16 THEN '16-18'
WHEN age <![CDATA[ <= ]]> 55 AND age >= 18 THEN '18-55'
WHEN age <![CDATA[ <= ]]> 60 AND age >= 56 THEN '56-60'
WHEN age >= 61 THEN '61'
END AS age
FROM
site_person_basic_info
WHERE
delete_flag =0
) AS a
GROUP BY
age