公式:环比增长率=(当月数据-上月数据)/上月数据
第一步首先统计出某年12个月+上年最后一个月份的数据,sql如下:
SELECT
a.`month` AS `month`,
ifnull( b.winOrderNum, 0 ) as winOrderNum,
ifnull( b.winOrderAmt, '0.00' ) as winOrderAmt
FROM
(
SELECT
CONCAT(#{date}-1,'-12') AS `month` UNION
SELECT
CONCAT(#{date},'-01') AS `month` UNION
SELECT
CONCAT(#{date},'-02') AS `month` UNION
SELECT
CONCAT(#{date},'-03') AS `month` UNION
SELECT
CONCAT(#{date},'-04') AS `month` UNION
SELECT
CONCAT(#{date},'-05') AS `month` UNION
SELECT
CONCAT(#{date},'-06') AS `month` UNION
SELECT
CONCAT(#{date},'-07') AS `month` UNION
SELECT
CONCAT(#{date},'-08') AS `month` UNION
SELECT
CONCAT(#{date},'-09') AS `month` UNION
SELECT
CONCAT(#{date},'-10') AS `month` UNION
SELECT
CONCAT(#{date},'-11') AS `month` UNION
SELECT
CONCAT( #{date},'-12') AS `month`
) a
LEFT JOIN (
SELECT
from_unixtime( tc.create_time / 1000, '%m' ) AS `month`,
count(tc.id) as winOrderNum,
CAST( IFNULL( sum( tc.amount ), 0 ) / 100 AS DECIMAL ( 20, 2 ) ) AS winOrderAmt
FROM
trade_contract tc
WHERE
from_unixtime( tc.create_time / 1000, '%Y' ) = #{date}
and tc.opportunity_id is not null
GROUP BY
`month`
) b ON a.`month` = b.`month`
第二步java处理环比增长:list为条件查询出的集合
需要注意的点:
1. 将查询的数据放到map<String,Object>对象中,通过key(月份)获取相应的数据
2. 获取当前时间的上个月日期
3. 通过给定的公式计算环比增长
这些都在for循环中处理完成
//定义map集合
Map<String, ContractReportDTO> map = list.stream().collect(Collectors.toMap(ContractReportDTO::getMonth, Function.identity()));
list.stream().forEach(entity -> {
ContractReportDTO lastContractReportDTO = map.get(DateUtils.getPreMonth(entity.getMonth()));
if (null == lastContractReportDTO) {
entity.setNumRate("0");
entity.setAmtRate("0");
} else {
//获取上月份的赢单数
Integer winOrderNumLast = lastContractReportDTO.getWinOrderNum();
if (winOrderNumLast == 0) {
entity.setNumRate("0");
} else {
//赢单数环比增长率=(当月数据-上月数据)/上月数据
BigDecimal numRate = new BigDecimal(0);
numRate = new BigDecimal(entity.getWinOrderNum()).subtract(new BigDecimal(winOrderNumLast)).divide(new BigDecimal(winOrderNumLast)).setScale(1, RoundingMode.HALF_UP);
entity.setNumRate(numRate.toString());
}
//获取上月份的赢单金额
String winOrderAmtLast = lastContractReportDTO.getWinOrderAmt();
if ("0.00".equals(winOrderAmtLast)) {
entity.setAmtRate("0");
} else {
//赢单金额环比增长率
BigDecimal amtRate = new BigDecimal(0);
amtRate = new BigDecimal(entity.getWinOrderAmt()).subtract(new BigDecimal(winOrderAmtLast)).divide(new BigDecimal(winOrderAmtLast)).setScale(1, RoundingMode.HALF_UP);
entity.setAmtRate(amtRate.toString());
}
}
});
list.remove(0);
获取当前时间的上个月日期方法这里也一并提供下:
/**
* 获取指定月份的上一月日期
*/
public static String getPreMonth(String month) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
return sdf.format(org.apache.commons.lang.time.DateUtils.addMonths(sdf.parse(month), -1));
} catch (Exception e) {
e.printStackTrace();
}
return "";
}