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

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

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

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

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

这里写图片描述

1. 控制器内容

    /**
     * [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. 库文件内容

    /**
     * [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;
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值