Sum top 5 values in MySQL

后端 未结 2 1402
礼貌的吻别
礼貌的吻别 2021-01-21 04:57

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 t

相关标签:
2条回答
  • 2021-01-21 05:36

    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 ;
    
    0 讨论(0)
  • 2021-01-21 05:44

    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;
    
    0 讨论(0)
提交回复
热议问题