3

我有一个 MySQL 表,我在其中存储赛车锦标赛的结果,因此每一行都包含 - 在其他数据中 - 每个车手在某场比赛中的位置。我想得到某个驱动程序的前 5 名的总和(例如,如果驱动程序的最佳位置是 1、2、2、4、5,我希望 MySQL 返回 14)。我想要做的是:

SELECT driver, SUM(position)
FROM results
WHERE (race, season, position) IN
   (SELECT race, season, position
    FROM results
    WHERE driver = "Vettel"
    ORDER BY position ASC
    LIMIT 5) 
AND driver = "Vettel"

当然,(种族、季节、位置)是“结果”表的主键。现在,问题是我不能真正让它工作,因为 MySQL 还不支持在内部子查询中使用 LIMIT。你会怎么做?

为了获得额外的积分 - 有没有办法通过一个查询来获得每个驱动程序的前 5 个结果的总和,而不是单个驱动程序?

4

2 回答 2

3

尝试这个:

SELECT driver, SUM(`position`)
FROM (SELECT driver, race, season, `position`, 
             IF(@lastDriver=(@lastDriver:=driver), @auto:=@auto+1, @auto:=1) indx 
      FROM results, (SELECT @lastDriver:=0, @auto:=1) A 
      ORDER BY driver, `position`) AS A  
WHERE indx <= 5 
GROUP BY driver ;
于 2013-01-12T14:04:41.367 回答
2

这是另一种方式...

SELECT a.season
     , a.driver
     , SUM(points) T5
  FROM
     ( SELECT x.season
            , x.driver
            , x.points
         FROM results x 
         JOIN results y 
           ON (y.season = x.season 
          AND y.driver = x.driver) 
          AND (y.position < x.position OR (y.position = x.position AND y.race < x.race))
        GROUP 
           BY x.season
            , x.driver
            , x.race
       HAVING COUNT(*) <=5
     ) a
 GROUP
    BY season
     , driver;
于 2013-01-12T14:49:32.767 回答