Sum top 5 values in MySQL

人走茶凉 提交于 2019-12-20 01:57:46

问题


I have a MySQL table where I store results from a racing championship, so that every rows contains -among other data- every driver's position in a certain race. I want to get the sum of a certain driver's top 5 placings (for instance, if a driver's best positions were 1,2,2,4,5, I'd like MySQL to return 14). What I'm trying to do is this:

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"

With (race, season, position) being a primary key for the "results" table, of course. Now, the problem is that I can't really get this to work , as MySQL doesn't yet support the use of LIMIT in inner subqueries. How would you do this?

And for extra credit - instead of a single driver, is there a way to get the sum of the top 5 results of every driver with a single query?


回答1:


Try this:

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 ;



回答2:


Here's another way...

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;


来源:https://stackoverflow.com/questions/14294003/sum-top-5-values-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!