SQL在GROUP BY中执行计算

时间:2016-08-18 09:32:41

标签: php postgresql laravel

这是我的代码:

$query = DB::table('notification');
        $query->leftJoin('rule', 'notification.rule_id', '=', 'rule.rule_id');
        $query->leftJoin('agent', 'notification.agent_id', '=', 'agent.agent_id')
                    ->leftJoin('department', 'agent.department_id', '=', 'department.department_id')
                    ->select(
                        DB::raw("coalesce(department.name, '$this->defaultDepartment') as tag"),
                        DB::raw('count(*) as count'),
                        //DB::raw('rule.quotient * count') as score
                        )
                    ->groupBy('tag')
                    ->orderBy('count', 'desc');

我想计算每个部门的得分:这是 部门中代理商的所有风险评分总和(按部门分组)。

FYI计算单个代理人得分(rule.quotient *规则数),即规则出现的数字。

我会提供一个db结构,但我认为查询会清除它。

我该如何解决?

此致

1 个答案:

答案 0 :(得分:1)

假设您的查询正确,laravel查询将如下所示:

$query = DB::table('notification');
        $query->leftJoin('rule', 'notification.rule_id', '=', 'rule.rule_id');
        $query->leftJoin('agent', 'notification.agent_id', '=', 'agent.agent_id')
                    ->leftJoin(DB::raw('(Select coalesce(department.name, '$this->defaultDepartment') as tag, count(*) as count from department)as department'),function($join){
                            $join->on('agent.department_id', '=', 'department.department_id')
                        ;})
                    ->groupBy('tag')
                    ->orderBy('count', 'desc');

更新

$query = DB::table('notification');        
$query->leftJoin('agent', 'notification.agent_id', '=', 'agent.agent_id')
            ->leftJoin(DB::raw('(Select coalesce(department.name, '$this->defaultDepartment') as tag, count(*) as count from department)as department'),function($join){
                    $join->on('agent.department_id', '=', 'department.department_id');
                ;})
$query->leftJoin(DB::raw('(Select (quotient * department.count) as score from rule) as rule'),function ($join){
                $join->on('rule', 'notification.rule_id', '=', 'rule.rule_id');
            });
        ->groupBy('tag')
        ->orderBy('count', 'desc');