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

2025-05-29 0 41

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

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

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

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

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

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数据的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持快网idc。

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

收藏 (0) 打赏

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

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 laravel实现按月或天或小时统计mysql数据的方法 https://www.kuaiidc.com/91407.html

相关文章

发表评论
暂无评论