您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息
三六零分类信息网 > 平顶山分类信息网,免费分类信息发布

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

2024/3/15 8:40:28发布27次查看
mysql教程栏目今天介绍如何优雅的统计订单收益,减少烦恼。
引言上篇文章详细说明了异构出收益日报表的方案.接下来我们来解决聚合需求多的情况下如何优化聚合sql的问题.
需求在如何优雅统计订单收益(一)中已经详细说明,大概就是些日/月/年的收益统计.
思考目标尽量减少聚合sql的查询次数给前端方便展示的api数据,表现在如果某一天的数据为空值时,后端处理成收益为0数据给前端方法函数尽量通用提高代码质量思路初步实现建立在已经通过canal异构出收益日统计表的情况下:
单日统计(例如今日,昨日,精确日期)可以直接通过日期锁定一条数据返回.月统计也可以通过时间过滤出当月的数据进行聚合统计.年统计也通过日期区间查询出所在年份的统计实现.各项收益也可以分别进行聚合查询这样看来日统计表的异构是有价值的,至少可以解决当前的所有需求.如果需要今日/昨日/上月/本月的收益统计,用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 '一级分销收益', `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<userincomedailyvo> userincomedailylist = selectincomebytimeinterval(userid, starttime, endtime); /给前端的数据需要把数据库存的分转为字符串,如果没有相关需求可跳过直接返回 list<userincomestatisticalvo> 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<string, string> getpersonalincomemap(int userid) { map<string, string> resultmap = new hashmap<>(4); localdate localdate = localdate.now(); //取出上个月第一天和这个月最后一天 string starttime = dateutil.getlastmonthfirstday().tostring(); string endtime = dateutil.getthismonthlastday().tostring(); //这条查询就是上面优化过的sql.传入开始和结束时间获得这个时间区间用户的收益日统计数据 list<userincomedailyvo> 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<userincomedailyvo> userincomedailylist, predicate<userincomedailyvo> predicate) { return userincomedailylist.stream() //过滤掉不符合条件的数据 .filter(predicate) //把流中对应的总收益字段取出 .maptoint(userincomedailyvo::gettotalincome) //聚合总收益 .sum(); }
扩展returntotalincomesum函数,maptoint支持传入tointfunction参数的值.
private int returntotalincomesum(list<userincomedailyvo> userincomedailylist, predicate<userincomedailyvo> predicate,tointfunction<userincomedailyvo> 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<userincomestatisticalvo> incomestatisticallist = new linkedlist<>(); //开始时间为今年的第一天 string starttime = dateutil.getthisyearfirstday.tostring(); //区间最大时间为今日 string endtime = localdate.now().tostring(); //通用sql list<userincomedailyvo> userincomedailylist = selectincomebytimeinterval(userid, starttime, endtime); //运用了stream的聚合,以月份进行分组,分组后用linkedhashmap接收防止分组后月份顺序错乱,完毕后再把得到的每个月的收益集合流进行聚合并组装成最终的实体返回 map<integer, userincomestatisticalvo> 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教程(视频)
以上就是优雅的统计订单收益(二)的详细内容。
平顶山分类信息网,免费分类信息发布

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录