MYSQL SUM用于不同表中的两个列

时间:2011-11-07 17:55:55

标签: mysql sql

我将解释方案,公式1,公式1中的每个团队有2个驱动程序,24个驱动程序,12个团队。我需要从team_stats表中获得下面计算的点数,但是从driver_stats表中得到杆位,领奖台和胜利,所以sebastion vettel和mark webber都是team_id ='3'的成员,这是红牛。我需要从driver_stats表中为每个人获得杆位,领奖台和胜利并将它们加在一起,但是从team_stats表中计算出其中TEAM的点数。我遇到的是它为每个team_id计算两次团队积分,因为在driver_stats表中有两个驱动程序,我只需要为team_stats表中的点执行SUM只为每个team_id驱动程序是...的成员。

DRIVER_STATS TABLE 
| track_id | drivers_id | qual_pos | race_pos | overtakes | points

TEAM STATS TABLE
| track_id | team_id | points |

DRIVERS TABLE
| driver_id | drivername | team_id |

TEAM TABLE COLUMNS 
|team_id | teamname | value

现在低于此功能但是计算了driver_stats表中的点数,它通过将两个驱动程序加在一起来正确地执行超车极点等的总和。我需要它来汇总team_stats表中每个team_id的点部分,而在该表中只有一个出现在driver_stats表中的每2个驱动程序,2个驱动程序到1个团队。

    SELECT t.teamname,
         t.value,
         SUM(IF(s.qual_pos = '1', 1,0)) AS poles,
         SUM(IF(s.race_pos <= '3', 1,0)) AS podiums,
         SUM(IF(s.race_pos = '1', 1,0)) AS victories,
         SUM(s.overtakes) AS overtakes,
         SUM(CASE
           WHEN s.track_id = (SELECT MAX(track_id) FROM driver_stats) THEN
             points
           ELSE
             0
         End) AS lastracepoints,
         SUM(points) AS points 

   FROM         drivers d
   INNER JOIN  driver_stats s
   ON         d.drivers_id = s.drivers_id
   AND         d.team_id = 3
   LEFT JOIN  teams t
   ON         d.team_id = t.team_id
   GROUP BY
   t.teamname

这是我改变它以试图实现它的查询。

       SELECT t.teamname,
         t.value,
         SUM(IF(s.qual_pos = '1', 1,0)) AS poles,
         SUM(IF(s.race_pos <= '3', 1,0)) AS podiums,
         SUM(IF(s.race_pos = '1', 1,0)) AS victories,
         SUM(s.overtakes) AS overtakes,
         SUM(CASE
           WHEN ts.track_id = (SELECT MAX(track_id) FROM team_stats) THEN
             ts.points
           ELSE
             0
         End) AS lastracepoints,
         SUM(ts.points) AS points 

   FROM          drivers d
   INNER JOIN  driver_stats s
   ON          d.drivers_id = s.drivers_id
   AND         d.team_id = 3
   LEFT JOIN  teams t
   ON          d.team_id = t.team_id
   INNER JOIN  team_stats ts
   ON          ts.team_id = d.team_id
   GROUP BY
   t.teamname

现在通过将team_stats连接到team_stats并将总和点更改为team_stats,数字有点失控,看起来它在driver_stats表中为driver_stats表中的每个驱动程序执行两次求和,其中i需要它做一次。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

ts.team_id不应该加入t.team_id,并查看INNER JOIN,你可能会更好地使用另一个LEFT JOIN