1. 程式人生 > >laravel實現按月或天或小時統計mysql資料

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; }