获取每个组的前三场比赛记录

时间:2019-02-26 11:03:41

标签: php mysql laravel

我运行此查询,该查询可以为我提供适当的数据。唯一的问题是我想要每个组的前3个记录;这将给我总计记录。

SELECT division_teams.division_id,division_teams.team_id,seasons.name,SUM(team_points.total) AS points 

FROM seasons 
INNER JOIN division_teams ON division_teams.season_id = seasons.id 
INNER JOIN team_points ON 
     eam_points.team_id = division_teams.team_id 
WHERE seasons.id = 19 
GROUP BY 
     division_teams.division_id,team_points.team_id 
ORDER BY division_id ASC,points DESC

表输出

enter image description here

1 个答案:

答案 0 :(得分:1)

对子查询使用自我联接

SELECT A.devision_id, A.team_id,A.name,a.points, COUNT(lesser.point) AS rank
FROM 
(SELECT division_teams.division_id,division_teams.team_id,seasons.name,SUM(team_points.total) AS points FROM seasons INNER JOIN division_teams ON division_teams.season_id = seasons.id INNER JOIN team_points ON eam_points.team_id = division_teams.team_id 
WHERE seasons.id = 19 GROUP BY division_teams.division_id,team_points.team_id
) A 
LEFT JOIN 
(SELECT division_teams.division_id,division_teams.team_id,seasons.name,SUM(team_points.total) AS points FROM seasons INNER JOIN division_teams ON division_teams.season_id = seasons.id INNER JOIN team_points ON eam_points.team_id = division_teams.team_id 
WHERE seasons.id = 19 GROUP BY division_teams.division_id,team_points.team_id
) AS lesser 
ON A.division_id = lesser.division_id  AND A.points < lesser.point
GROUP BY A.devision_id, A.team_id,A.name,a.points
HAVING COUNT(lesser.point) < 3
ORDER BY A.division_id ASC,A.points DESC