0

我在浏览我的表并将我的 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

表

4

1 回答 1

1

您应该在单个查询中使用 group by 而不是嵌套(您拥有它的方式)。这是处理它的一种方法:

SELECT  `user_challenge`.`team_id` ,  `teams`.`name` , SUM(`userStepSum`) as `TeamStepSum`
FROM  `user_challenge` 
INNER JOIN  `users` ON  `user_challenge`.`user_id` =  `users`.`id` 
INNER JOIN  `teams` ON  `user_challenge`.`team_id` =  `teams`.`id` 
INNER JOIN 
(
SELECT activities.user_id, SUM( activities.steps ) as `userStepSum`
FROM activities
where 
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'
GROUP BY `activities`.`user_id`
) `user_steps` on `user_steps`.`user_id` = `user_challenge`.`user_id`
WHERE  `user_challenge`.`challenge_id` =2
AND  `user_challenge`.`team_id` IS NOT NULL 
GROUP BY  `user_challenge`.`team_id`

您也可以直接加入活动。祝你好运。

于 2013-09-18T17:28:56.030 回答