Sum top 5 values in MySQL

后端 未结 2 1432
礼貌的吻别
礼貌的吻别 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: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;
    

提交回复
热议问题