0

我有一个类似于这个问题的问题,但有点复杂,我无法弄清楚如何有效地做到这一点。给定两张表,一张是运动员名单,一张是他们参加过的比赛的名单,例如,

运动员

  • ID
  • 姓名
  • 性别
  • 细节

比赛

  • 运动员编号
  • 积分

我想仅使用他们的前 4 名比赛完成(其中“顶级”由积分定义)在给定的年份按性别对所有运动员进行排名。我觉得我应该能够在子查询中执行此操作,但我不知道如何从内部引用外部查询。我现在的样子是这样的:

SELECT SUM(points) as points, a.* FROM
(SELECT rr.points, inner_a.id as athlete_id 
FROM athletes_raceresult rr 
INNER JOIN athletes_athlete inner_a ON rr.athlete_id = inner_a.id
WHERE inner_a.gender ='m' AND rr.year BETWEEN 2012 AND 2014 
AND inner_a.id = a.id
ORDER BY rr.points DESC) as races 
INNER JOIN athletes_athlete a ON races.athlete_id = a.id
GROUP BY races.athlete_id 
ORDER BY points DESC

但这并不限制每个运动员的得分为 4 行。看起来我想要一个相关的子查询,但我无法让它工作。

4

1 回答 1

2

以下SQL Fiddle示例说明了如何做到这一点:

SELECT SUM(rr.points), a.id 
FROM athletes_raceresult AS rr 
INNER JOIN athletes_athlete AS a ON rr.athlete_id = a.id
WHERE (
  SELECT count(crr.points)
  FROM athletes_raceresult AS crr 
  INNER JOIN athletes_athlete AS ca ON crr.athlete_id = ca.id
  WHERE ca.gender = 'm' 
  AND crr.year BETWEEN 2012 AND 2014 
  AND crr.athlete_id = a.id AND crr.points >= rr.points
) <= 4
AND a.gender = 'm' 
AND rr.year BETWEEN 2012 AND 2014 
GROUP BY a.id
于 2013-11-06T19:24:54.443 回答