百分百源码网-让建站变得如此简单! 登录 注册 签到领金币!

主页 | 如何升级VIP | TAG标签

当前位置: 主页>网站教程>数据库> 优雅的统计订单收益(二)
分享文章到:

优雅的统计订单收益(二)

发布时间:11/01 来源:未知 浏览: 关键词:
mysql教程栏目今天介绍怎样优雅的统计订单收益,减少懊恼。 mysql教程栏目今天介绍怎样优雅的统计订单收益,减少懊恼。

引言

上篇文章细致注明了异构出收益日报表的方案.接下来我们来解决聚合需求多的状况下怎样优化聚合SQL的题目.

需求

在怎样优雅统计订单收益(一)中已经细致注明,大约就是些日/月/年的收益统计.

思索

指标

  • 尽量减少聚合SQL的查询次数
  • 给前端利便展现的API数据,体现在要是某一天的数据为空值时,后端处置成收益为0数据给前端
  • 办法函数尽量通用提高代码质量

思绪

初步实现

创立在已经通过canal异构出收益日统计表的状况下:

  1. 单日统计(例如今日,昨日,精准日期)可以直接通过日期锁定一条数据返回.
  2. 月统计也可以通过工夫过滤出当月的数据进行聚合统计.
  3. 年统计也通过日期区间查询出所在年份的统计实现.
  4. 各项收益也可以离别进行聚合查询

这样看来日统计表的异构是有价值的,至少可以解决目前的所有需求. 要是需要今日/昨日/上月/本月的收益统计,用SQL直接聚合查询,则需要离别查询今日,昨日以及跨度为整月的数据集然后通过SUM聚合实现.

CREATE TABLE `t_user_income_daily` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `user_id` int(11) NOT NULL COMMENT '会员id',
  `day_time` date NOT NULL COMMENT '日期',
  `self_purchase_income` int(11) DEFAULT '0' COMMENT '自购收益',
  `member_income` int(11) DEFAULT '0' COMMENT '1级分销收益',
  `affiliate_member_income` int(11) DEFAULT '0' COMMENT '二级分销收益',
  `share_income` int(11) DEFAULT '0' COMMENT '分享收益',
  `effective_order_num` int(11) DEFAULT '0' COMMENT '有效订单数',
  `total_income` int(11) DEFAULT '0' COMMENT '总收益',
  `update_time` datetime DEFAULT NULL COMMENT '更新工夫',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8 COMMENT='会员收益日统计'

这种写法要是接口需要返回今日/昨日/上月/本月的收益统计时,就需要查询4次SQL才可以实现.写法没题目,但是不是最优解?可以用更少的SQL查询么?

调查

通过调查剖析,今日/昨日/上月/本月统计存在共同的交集,它们都处于统一个工夫区间(上月一号-本月月底),那我们可以通过SQL直接查出这两个月的数据,再通历程序聚合就可以轻松得出我们想要的数据.

优化实现

增补一下收益日统计表设计

select * from t_user_income_daily where day_time BETWEEN '上月一号' AND '本月月底' and user_id=xxx

查询出两个月的收益

select * from t_user_income

为了减少表的数据量,要是当日没有收益变更是不会新建当日的日统计数据的,所以这里只能查询出某工夫区间会员有收益变更的收益统计数据.要是处置某一天数据为空的状况则还需要再程序中特别处置.此处有小妙招,在数据库中生成一张工夫辅助表.以天为单位,寄存各种格局化后的工夫数据,辅助查询细致操纵可见这篇博文Mysql生成工夫辅助表.有了这张表就可以进一步优化这条SQL.工夫辅助表的格局如下,也可修改存储历程,参加本人个性化的工夫格局.

 SELECT
        a.DAY_ID day_time,
        a.MONTH_ID month_time,
        a.DAY_SHORT_DESC day_time_str,
        CASE when b.user_id is null then #{userId} else b.user_id end user_id,
        CASE when b.self_purchase_income is null then 0 else b.self_purchase_income end self_purchase_income,
        CASE when b.member_income is null then 0 else b.member_income end member_income,
        CASE when b.affiliate_member_income is null then 0 else b.affiliate_member_income end affiliate_member_income,
        CASE when b.share_income is null then 0 else b.share_income end share_income,
        CASE when b.effective_order_num is null then 0 else b.effective_order_num end effective_order_num,
        CASE when b.total_income is null then 0 else b.total_income end total_income
        FROM
        t_day_assist a
        LEFT JOIN t_user_income_daily b ON b.user_id = #{userId}
        AND a.DAY_SHORT_DESC = b.day_time
        WHERE
        STR_TO_DATE( a.DAY_SHORT_DESC, '%Y-%m-%d' ) BETWEEN #{startTime} AND #{endTime}
        ORDER BY
        a.DAY_ID DESC

思绪很简略,用工夫辅助表左关联需要查询的收益日统计表,关联字段就是day_time工夫,要是没有当天的收益数据,SQL中也会有日期为那一天但是统计数据为空的数据,用casewhen判空赋值给0,最后通过工夫倒序,便可以查询出一套完备工夫区间统计.

终究实现

以SQL查询出的数据为根基.在程序中用stream进行聚合. 举例注明一些例子,先从简略的开端

常用静态办法封装

/**
     * @description: 本月的首先天
     * @author: chenyunxuan
     */
    public static LocalDate getThisMonthFirstDay() {
        return LocalDate.of(LocalDate.now().getYear(), LocalDate.now().getMonthValue(), 1);
    }

    /**
     * @description: 本月的最后一天
     * @author: chenyunxuan
     */
    public static LocalDate getThisMonthLastDay() {
        return LocalDate.now().with(TemporalAdjusters.lastDayOfMonth());
    }

    /**
     * @description: 上个月首先天
     * @author: chenyunxuan
     */
    public static LocalDate getLastMonthFirstDay() {
        return LocalDate.of(LocalDate.now().getYear(), LocalDate.now().getMonthValue() - 1, 1);
    }

    /**
     * @description: 上个月的最后一天
     * @author: chenyunxuan
     */
    public static LocalDate getLastMonthLastDay() {
        return getLastMonthFirstDay().with(TemporalAdjusters.lastDayOfMonth());
    }
    
    /**
     * @description: 本年的首先天
     * @author: chenyunxuan
     */
    public static LocalDate getThisYearFirstDay() {
        return LocalDate.of(LocalDate.now().getYear(), 1, 1);
    }
    
    /**
     * @description: 分转元,不支撑负数
     * @author: chenyunxuan
     */
    public static String fenToYuan(Integer money) {
        if (money == null) {
            return "0.00";
        }
        String s = money.toString();
        int len = s.length();
        StringBuilder sb = new StringBuilder();
        if (s != null && s.trim().length() > 0) {
            if (len == 1) {
                sb.append("0.0").append(s);
            } else if (len == 2) {
                sb.append("0.").append(s);
            } else {
                sb.append(s.substring(0, len - 2)).append(".").append(s.substring(len - 2));
            }
        } else {
            sb.append("0.00");
        }
        return sb.toString();
    }

指定月份收益列表(定时间倒序)

public ResponseResult selectIncomeDetailThisMonth(int userId, Integer year, Integer month) {
        ResponseResult responseResult = ResponseResult.newSingleData();
        String startTime;
        String endTime;
        //不是指定月份
        if (null == year && null == month) {
            //要是工夫为当月则只显示今日到当月一号
            startTime = DateUtil.getThisMonthFirstDay().toString();
            endTime = LocalDate.now().toString();
        } else {
            //要是是指定年份月份,用LocalDate.of构建出需要查询的月份的一号日期和最后一天的日期
            LocalDate localDate = LocalDate.of(year, month, 1);
            startTime = localDate.toString();
            endTime = localDate.with(TemporalAdjusters.lastDayOfMonth()).toString();
        }
        //查询用通用的SQL传入会员id和开端完毕工夫
        List userIncomeDailyList = selectIncomeByTimeInterval(userId, startTime, endTime);
        /给前端的数据需要把数据库存的分转为字符串,要是没有相干需求可跳过直接返回
        List userIncomeStatisticalList = userIncomeDailyList.stream()
                .map(item -> UserIncomeStatisticalVO.builder()
                        .affiliateMemberIncome(Tools.fenToYuan(item.getAffiliateMemberIncome()))
                        .memberIncome(Tools.fenToYuan(item.getMemberIncome()))
                        .effectiveOrderNum(item.getEffectiveOrderNum())
                        .shareIncome(Tools.fenToYuan(item.getShareIncome()))
                        .totalIncome(Tools.fenToYuan(item.getTotalIncome()))
                        .dayTimeStr(item.getDayTimeStr())
                        .selfPurchaseIncome(Tools.fenToYuan(item.getSelfPurchaseIncome())).build()).collect(Collectors.toList());
        responseResult.setData(userIncomeStatisticalList);
        return responseResult;
    }

今日/昨日/上月/本月收益

    public Map getPersonalIncomeMap(int userId) {
        Map resultMap = new HashMap<>(4);
        LocalDate localDate = LocalDate.now();
        //取出上个月第一天和这个月最后一天
        String startTime = DateUtil.getLastMonthFirstDay().toString();
        String endTime = DateUtil.getThisMonthLastDay().toString();
        //这条查询就是上面优化过的SQL.传入开始和结束时间获得这个时间区间用户的收益日统计数据
        List userIncomeDailyList = selectIncomeByTimeInterval(userId, startTime, endTime);
        //由于这里需要取的都是总收益,所以封装了returnTotalIncomeSum办法,用于传入前提返回总收益聚合
        //第二个参数就是筛选前提,只保存相符前提的局部.(此处都是用的LocalDate的API)
        int today = returnTotalIncomeSum(userIncomeDailyList, n -> localDate.toString().equals(n.getDayTimeStr()));
        int yesterday = returnTotalIncomeSum(userIncomeDailyList, n -> localDate.minusDays(1).toString().equals(n.getDayTimeStr()));
        int thisMonth = returnTotalIncomeSum(userIncomeDailyList, n ->
                n.getDayTime() >= Integer.parseInt(DateUtil.getThisMonthFirstDay().toString().replace("-", ""))
                        && n.getDayTime() <= Integer.parseInt(DateUtil.getThisMonthLastDay().toString().replace("-", "")));
        int lastMonth = returnTotalIncomeSum(userIncomeDailyList, n ->
                n.getDayTime() >= Integer.parseInt(DateUtil.getLastMonthFirstDay().toString().replace("-", ""))
                        && n.getDayTime() <= Integer.parseInt(DateUtil.getLastMonthLastDay().toString().replace("-", "")));
        //因为客户端显示的是两位小数的字符串,所以需要用Tools.fenToYuan把数值金额转换成字符串
        resultMap.put("today", Tools.fenToYuan(today));
        resultMap.put("yesterday", Tools.fenToYuan(yesterday));
        resultMap.put("thisMonth", Tools.fenToYuan(thisMonth));
        resultMap.put("lastMonth", Tools.fenToYuan(lastMonth));
        return resultMap;
    }
    
    //传入收益集合以及过滤接口,返回对应集合数据,Predicate接口是返回一个boolean类型的值,用于筛选
    private int returnTotalIncomeSum(List userIncomeDailyList, Predicate predicate) {
        return userIncomeDailyList.stream()
                //过滤掉不相符前提的数据
                .filter(predicate)
                //把流中对应的总收益字段掏出
                .mapToInt(UserIncomeDailyVO::getTotalIncome)
                //聚合总收益
                .sum();
    }

扩展returnTotalIncomeSum函数,mapToInt支撑传入ToIntFunction参数的值.

     private int returnTotalIncomeSum(List userIncomeDailyList, Predicate predicate,ToIntFunction function) {
        return userIncomeDailyList.stream()
                //过滤掉不相符前提的数据
                .filter(predicate)
                //把流中对应的字段掏出
                .mapToInt(function)
                //聚合收益
                .sum();
例如:
    今日分享的金额,function参数传入`UserIncomeDailyVO::getShareIncome`
    今日自购和分享的金额,funciton参数传入`userIncomeDailyVO->userIncomeDailyVO.getShareIncome()+userIncomeDailyVO.getSelfPurchaseIncome()`
}

本年的收益数据(聚合按月展现)

我们先来理解一下stream的聚合 语法糖:

      list.stream().collect(
            Collectors.groupingBy(分组字段,
                     Collectors.collectingAndThen(Collectors.toList(), 
                     list -> {分组后的操纵})
            ));

流程图:代码实例:

 public ResponseResult selectIncomeDetailThisYear(int userId) {
        ResponseResult responseResult = ResponseResult.newSingleData();
        List incomeStatisticalList = new LinkedList<>();
        //开始时间为今年的第一天
        String startTime = DateUtil.getThisYearFirstDay.toString();
        //区间最大时间为今日
        String endTime = LocalDate.now().toString();
        //通用SQL
        List userIncomeDailyList = selectIncomeByTimeInterval(userId, startTime, endTime);
        //使用了stream的聚合,以月份进行分组,分组后用LinkedHashMap接收防止分组后月份次序错乱,结束后再把得到的每个月的收益汇合流进行聚合并组装成终究的实体返回
        Map resultMap = userIncomeDailyList.parallelStream()
                .collect(Collectors.groupingBy(UserIncomeDailyVO::getMonthTime, LinkedHashMap::new,
                        Collectors.collectingAndThen(Collectors.toList(), item -> UserIncomeStatisticalVO.builder()
                                .affiliateMemberIncome(Tools.fenToYuan(item.stream().mapToInt(UserIncomeDailyVO::getAffiliateMemberIncome).sum()))
                                .memberIncome(Tools.fenToYuan(item.stream().mapToInt(UserIncomeDailyVO::getMemberIncome).sum()))
                                .effectiveOrderNum(item.stream().mapToInt(UserIncomeDailyVO::getEffectiveOrderNum).sum())
                                .shareIncome(Tools.fenToYuan(item.stream().mapToInt(UserIncomeDailyVO::getShareIncome).sum()))
                                .totalIncome(Tools.fenToYuan(item.stream().mapToInt(UserIncomeDailyVO::getTotalIncome).sum()))
                                .monthTimeStr(item.stream().map(time -> {
                                    String timeStr = time.getMonthTime().toString();
                                    return timeStr.substring(0, timeStr.length() - 2).concat("-").concat(timeStr.substring(timeStr.length() - 2));
                                }).findFirst().get())
                                .selfPurchaseIncome(Tools.fenToYuan(item.stream().mapToInt(UserIncomeDailyVO::getSelfPurchaseIncome).sum())).build()))
                );
        resultMap.forEach((k, v) -> incomeStatisticalList.add(v));
        responseResult.setData(incomeStatisticalList);
        return responseResult;
    }

总结

本文主要介绍了在统计收益时,一些SQL的优化小技巧JDK中stream聚合. 总结下来就是在业务量逐步增大时,尽量以免屡次大数目量表的查询聚合,可以剖析思索后用尽量少的聚合查询完成,一些简略的业务也可以直接程序聚合.以免屡次数据库查询的开销.在客户端返回接口需要工夫完备性时,可以考虑工夫辅助表进行关联,可以减少程序盘算空值判空操纵,优化代码的质量.

相干免费学习举荐:mysql教程(视 频)

以上就是优雅的统计订单收益(二)的细致内容,更多请关注 百分百源码网 其它相干文章!

打赏

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

百分百源码网 建议打赏1~10元,土豪随意,感谢您的阅读!

共有152人阅读,期待你的评论!发表评论
昵称: 网址: 验证码: 点击我更换图片
最新评论

本文标签

广告赞助

能出一分力是一分吧!

订阅获得更多模板

本文标签

广告赞助

订阅获得更多模板