laravel实现按月或天或小时统计mysql数据的方法

吾爱主题 阅读:114 2021-08-27 15:33:00 评论:0

在PHP里怎么比较简单的实现按时间(如按月,按天,按小时)来统计表里的数据呢?

如:要实现获取下图曲线图数据(ps:当然也可能是柱状图等,数据都是一样的),默认获取七天内的数据,点击今天,7天,15天,30天可任意切换,其中今天是按小时统计.

不过我的实现方法有一个小缺点,当某个小时内是没有数据的,那么该小时不会出现,不过这个应该可以通过前端的形式弥补

好了,废话不多说,上图上代码!

1. 控制器内容

?
1 2 3 4 5 6 7 8 9 /**   * [getsellerdata 获取某时间段内商户结算查询数据]   * @param Request $request [description] start:起始时间 end:结束时间   * @return [type]      [description]   */ public function getsellerqudata(Request $request ){    $data = $this ->dataanalysis->getSellerQuData( $request ->start, $request -> end );    return $data ;    }

2. 库文件内容

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 /**    * [getSellerQuData 获取商户结算数据 曲线]    * @param [string] $start [起始时间]2017-08    * @param [string] $end  [结束时间]    * @return [type]    [description]    */   public function getSellerQuData( $name , $start , $end ){       //计算时间差值,以决定格式化时间格式     $diff = strtotime ( $end )- strtotime ( $start );       //分组条件 1天内按小时分组,否则按天/月分组     //86400/1天 2678400/1月     if ( $diff <86400&& $diff >0){       $sort = '%H' ;     } elseif ( $diff <2678400){       $sort = '%Y-%m-%d' ;     } else {       $sort = '%Y-%m' ;     }     //把数据添加时间按格式化时间分组求和,求和分两种,一种是直接求和,一种是满足case when条件的数据求和     $query = DB::table( 'user_withdrawals as w' )->select(DB::raw( "FROM_UNIXTIME(created_at,'{$sort}') as thedata,sum(case when w.cash_type = 1 then w.money end) as xiabi,sum(case when w.cash_type = 2 then w.money end) as online,sum(w.money) as alls" ))->groupBy(DB::raw( "FROM_UNIXTIME(created_at,'{$sort}')" ));       //条件筛选 某时间段内     if ( ! empty ( $start ) ){       $query ->whereRaw( 'w.created_at >= ?' , strtotime ( $start ));     }     if ( ! empty ( $end ) ){       $query ->whereRaw( 'w.created_at <= ?' , strtotime ( $end ));     }       $data = $query ->get();       return $data ;   }

以上这篇laravel实现按月或天或小时统计mysql数据的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/php_girl/article/details/76681366

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容