如何获得总用户平均经过7天的时间

时间:2019-02-27 09:25:02

标签: mysql laravel phpmyadmin

我想获取过去7天的每日总用户平均使用时间,我为每个用户编写了SQL的平均时间,但是现在我在LARAVEL SQL函数中有问题,请帮助修复此SQL。 / p>

$currentTime = Carbon::today();

    $userUsage = DB::table('active_user')
                ->select(DB::raw('acu_name as name'),
                    DB::raw('u_fname as fname'),
                    DB::raw('AVG(TIMESTAMPDIFF(MINUTE,acu_at,acu_et)) as averageTime'),
                    DB::raw('count(*) as number'))
                ->join('u_info_one', 'active_user.acu_name', '=', 'u_info_one.u_email')
                ->whereDate('acu_at', '<=', $currentTime)
                ->groupBy('acu_name')
                ->get();

enter image description here

2 个答案:

答案 0 :(得分:1)

您需要为此使用GROUP BY,例如:

$userUsage = DB::table('active_user')
                ->select(DB::raw('acu_name as name'),
                    DB::raw('u_fname as fname'),
                    DB::raw('AVG(TIMESTAMPDIFF(MINUTE,acu_at,acu_et)) as averageTime'),
                    DB::raw('count(*) as number'))
                ->join('u_info_one', 'active_user.acu_name', '=', 'u_info_one.u_email')
                ->whereDate('acu_at', '<=', $currentTime)
                ->groupBy('acu_name', DB::raw('DATE(acu_at)'))
                ->get();

更新

如果您只需要所有用户的每日平均值,则可以从分组依据中删除acu_name,例如:

$userUsage = DB::table('active_user')
                ->select(DB::raw('acu_name as name'),
                    DB::raw('u_fname as fname'),
                    DB::raw('AVG(TIMESTAMPDIFF(MINUTE,acu_at,acu_et)) as averageTime'),
                    DB::raw('count(*) as number'))
                ->join('u_info_one', 'active_user.acu_name', '=', 'u_info_one.u_email')
                ->whereDate('acu_at', '<=', $currentTime)
                ->groupBy(DB::raw('DATE(acu_at)'))
                ->get();

答案 1 :(得分:0)

正确答案是

    $userUsage = DB::table('active_user')
                ->select(DB::raw('DATE(acu_at) as date'),
                    DB::raw('AVG(TIMESTAMPDIFF(MINUTE,acu_at,acu_et)) as averageTime'),
                    DB::raw('COUNT(DISTINCT `acu_name`) as users'))
                ->join('u_info_one', 'active_user.acu_name', '=', 'u_info_one.u_email')
                ->whereDate('acu_at', '<=', $currentTime)
                ->groupBy(DB::raw('DATE(acu_at)'))
                ->orderBy(DB::raw('DATE(acu_at)'))
                ->get();

foreach($userUsage as $usUa)
   {
     $avegTime = ($usUa->averageTime/$usUa->users);
     echo "['".$usUa->date."',".$avegTime."],";
   }