简体   繁体   中英

Get top three match records from each group

I run this query which gives me proper data. The only problem is that I want the top 3 records from each group; this will give me total records.

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

table output

在此处输入图片说明

Use self join with subquery

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM