将一列除以从子查询创建的另一列

时间:2018-10-20 18:23:59

标签: laravel mysqli

我有这个查询-

$employees = Employee::where('user_id', $user->id)->withCount([
                        'answers as questions_received' => function ($query) use($date) {
                            $query->where('created_at', '>=', $date);
                        }, 
                        'answers as correct' => function ($query) use($date) {
                            $query->where('correct', 1)->where('created_at', '>=', $date);
                        }
                    ]);


$employees = $employees
                        ->orderBy('answered', 'desc')
                        ->orderBy('correct', 'desc')
                        ->get();

我想做这样的事情-((correct/questions_received) * 100) as percentage 但是不知道该怎么做。请帮忙:)

谢谢

1 个答案:

答案 0 :(得分:0)

假设这是表布局,并且answeredcorrect列的数据类型的值为0和1(例如Laravel将tinyint(1)数据类型用于MySQL的布尔值)

Employees
+----+---------+
| id | user_id |
+----+---------+

Answers
+----+-------------+----------+---------+------------+
| id | employee_id | answered | correct | created_at |
+----+-------------+----------+---------+------------+

这似乎可以解决问题:

$employees = Employee::select('E.*')
    ->selectRaw('COUNT(*) AS questions_received')
    ->selectRaw('SUM(correct) AS correct')
    ->selectRaw('SUM(correct) / COUNT(*) * 100 AS percentage')
    ->from('employees AS E')
    ->join('answers AS A', 'E.id', '=', 'A.employee_id')
    ->where('A.created_at', '>=', $date)
    ->where('E.user_id', $user->id)
    ->groupBy('E.id')
    ->get();