来自两个表的MYSQL QUERY sum

时间:2011-11-06 14:30:55

标签: mysql sql

嘿,我在下面的Mysql查询中遇到了一些麻烦,如何从team_stats表而不是driver_stats表中计算SUMS(计算点,查询中的第5和第6个总和),还可以使用与team_id = 3的情况相同。我所需要的只是将那些计算从driver_stats表交换到team_stats表,我遇到的问题是当我尝试这样做时,计算方法很高,就像它是不仅仅是为了team_id ='3'或者其他任何数字。

任何帮助都会非常感谢。

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

             # CHANGE THIS SUM AND THE SUM ABOVE TO CALCULATE
             # the points column in the tale named TEAM_STATS
             # but with the same restrictions as now,
             # only where team_id = 3
             SUM(points) AS points 

FROM         driver_stats s
  LEFT JOIN  drivers d
  ON         d.drivers_id = s.drivers_id
  LEFT JOIN  teams t
  ON         d.team_id = t.team_id
WHERE        d.team_id = 3

1 个答案:

答案 0 :(得分:0)

MySQL可以让你使用聚合(总和),而不是在特殊情况下定义group by子句,但它不典型,不适合你。

Is it possible to use Aggregate function in a Select statment without using Group By clause?

我没有通过尝试来测试这个:

SELECT       t.teamname,
             t.value,
             SUM(IF(qual_pos = '1', 1,0)) AS poles,
             SUM(IF(race_pos <= '3', 1,0)) AS podiums,
             SUM(IF(race_pos = '1', 1,0)) AS victories,
             SUM(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
    teamname,
    `value`