本篇来介绍dwz table增加总计、小计,总计代表所有分页的数据总和,小计代表当前页面的数据总和。
我先说明一下小计和总计的概念,假如当前查询结果有100条记录,当前页显示50条,其中有一列是统计资金综合的,假如每个人当前资金为1元,那么第一页的小计就是50元,总计就是100元,那么如果处理好这个数据统计呢,下面是我们当前执行的方案,显示效果见下图
第一步,查询出列表
<select id="getDepositListBySelective" resultType="hashmap" parameterType="map">
select m.username username, d.RealName realname,
COALESCE (d.BeginMoney, 0) AS beginmoney,
COALESCE (d.InMoney,0) AS inmoney ,
第二步,查询出总计
<select id="getDeposittotalListBySelective" resultType="hashmap" parameterType="map">
SELECT '总计:' username,'' realname,
COALESCE (ROUND(SUM(d.BeginMoney),2), 0) AS beginmoney,
COALESCE (ROUND(SUM(d.InMoney),2),0) AS inmoney ,
第三步,通过调用小计计算方法得出列表、小计、总计的列表
List dailyDepositlist = listWithSumByTwoZero(
this.reportMapper.getDepositListBySelective(vo, vo.createRowBounds()),
this.reportMapper.getDeposittotalListBySelective(vo));
第四步,关键的小计算法,首先通过一次数据循环,根据列关键字,得出需要计算小计的当前列的小计
protected List listWithSumByTwoZero(List preList, List totalList) {
// 获取总计数据,获知那一列需要进行小记
Map totalMap = (Map) totalList.get(0);
// 获取总计的key
Iterator keySet = totalMap.keySet().iterator();
// 创建一行小计
Map subTotalMap = new HashMap();
// 统计小计需要计算的列
Map<String, BigDecimal> shouldSumMap = new HashMap<String, BigDecimal>();
List<String> shouldSumList = new ArrayList<String>();
// 初始化
while (keySet.hasNext()) {
String key = (String) keySet.next();
Object totalValue = totalMap.get(key);
if (totalValue.equals("总计:")) {
subTotalMap.put(key, "小计:");
}
// 如果当前列不需要统计
else if (totalValue.equals("")) {
subTotalMap.put(key, totalValue);
} else {
shouldSumMap.put(key, BigDecimal.ZERO);
shouldSumList.add(key);
subTotalMap.put(key, 0);
}
}
// 如果获取的list不为空
if (preList != null && preList.size() > 0) {
// 对需要统计小计的进行计算
for (int i = 0; i < preList.size(); i++) {
Map preMap = (Map) preList.get(i);
for (String key : shouldSumList) {
BigDecimal temp = shouldSumMap.get(key);
BigDecimal preDecimal = new BigDecimal(preMap.get(key).toString());
temp = temp.add(preDecimal);
shouldSumMap.put(key, temp);
}
}
}
// 计算过的数据进行更新
for (String key : shouldSumMap.keySet()) {
subTotalMap.put(key, shouldSumMap.get(key));
}
preList.add(subTotalMap);
preList.add(totalMap);
return preList;
}
总结:小计的算法虽然能够在一次循环查询出多个小计结果,但是总感觉不够简便,另外列表和总计的查询,总觉得性能很差。