laravel實現按月、按天、按小時統計mysql的數據

利用mysql 的條件統計

要實現獲取下圖曲線圖數據(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;        
}

4. 查詢類的實現方法

    /**
     * [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;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章