我在浏览我的表并将我的 SQL 语句构造为 GROUP BY team_id 时遇到了一些麻烦(使用 Laravel 4 Fluent)。如果我删除 GROUP BY,我将获得每个用户的总步数。但我需要的是每个团队的总步数。
SQL 语句:
SELECT `user_challenge`.`team_id` , `teams`.`name` , (
SELECT SUM( activities.steps )
FROM activities
WHERE activities.user_id = users.id
AND activities.created_at <= '2013-11-30 15:32:45'
AND activities.date >= '2013-10-01 15:32:45'
AND activities.date <= '2013-11-30 15:32:45'
) AS steps
FROM `user_challenge`
INNER JOIN `users` ON `user_challenge`.`user_id` = `users`.`id`
INNER JOIN `teams` ON `user_challenge`.`team_id` = `teams`.`id`
WHERE `user_challenge`.`challenge_id` =2
AND `user_challenge`.`team_id` IS NOT NULL
GROUP BY `user_challenge`.`team_id`
PHP(Laravel)如果有帮助:
$subquery = "(SELECT SUM(activities.$type) FROM activities WHERE activities.user_id = users.id AND activities.created_at <= '". $challenge->end_date ."' AND activities.date >= '". $challenge->start_date ."' AND activities.date <= '". $challenge->end_date ."') as $type";
$teams = DB::table('user_challenge')
->where('user_challenge.challenge_id', $challenge->id)
->whereNotNull('user_challenge.team_id')
->join('users','user_challenge.user_id','=','users.id')
->join('teams','user_challenge.team_id','=','teams.id')
->select('user_challenge.team_id', 'teams.name',DB::raw($subquery))
->groupBy('user_challenge.team_id')
->get();
使用 GROUP BY 输出:
team_id, name, steps
1, Team 1, null
没有 GROUP BY 的输出:
team_id, name, steps
1, Team 1, null
1, Team 1, 13000
1, Team 1, 10000
期望的输出:
team_id, name, steps
1, Team 1, 23000