从mysql中的表中检索5个最高分的总和

时间:2013-10-05 07:26:52

标签: php html mysql sql codeigniter-2

我正在开展一个项目,我需要从表格中按降序排序每个团队的前5名score_rank。 这是表结构

enter image description here

这是结构的链接

http://kolkata-web-design.co.in/test/structure.htm

这是我正在尝试的查询

SELECT team_id AS `team` ,  (SELECT SUM(score_rank)
FROM `contest_result_total`
WHERE team = `team_id`
ORDER BY score_rank DESC
LIMIT 5
) AS `score`
FROM `contest_result_total`
GROUP BY team_id
ORDER BY `score` DESC

但它没有给出前5名的分数,而是计算所有比赛的总和,而不仅仅是按球队ID分组的

任何人都可以帮助我。 感谢

2 个答案:

答案 0 :(得分:1)

SELECT team_id,sum(score_rank)
FROM contest_result_total
WHERE (SELECT COUNT(*)
      FROM contest_result_total AS c
      WHERE c.team_id = contest_result_total.team_id
        AND contest_result_total.score_rank <= c.score_rank) <= 5
GROUP BY team_id

答案 1 :(得分:0)

试试这个:

SELECT team_id AS `team` ,  (SELECT SUM(score_rank)
FROM `contest_result_total`
WHERE team = `team_id`
GROUP BY team_id
ORDER BY score_rank DESC
LIMIT 5
) AS `score`
FROM `contest_result_total`
ORDER BY `score` DESC