SQL Sum返回错误的数字

时间:2015-05-19 19:25:22

标签: sql

我加起来为体育赛事出售的门票数量,答案应该在100以下,但我的回答是成千上万。

SELECT Stubhub.Active.Opponent, 
       SUM(Stubhub.Active.Qty) AS AQty, SUM(Stubhub.Sold.Qty) AS SQty
FROM   Stubhub.Active INNER JOIN
       Stubhub.Sold ON Stubhub.Active.Opponent = Stubhub.Sold.Opponent
GROUP BY Stubhub.Active.Opponent

1 个答案:

答案 0 :(得分:0)

这是一种问题,因为你在每张桌子之间为每个对手获得一个笛卡尔积。解决方案是由对手预先聚合:

SELECT a.Opponent, a.AQty, s.SQty
FROM (SELECT a.Opponent, SUM(a.Qty) as AQty
      FROM Stubhub.Active a
      GROUP BY a.Opponent
     ) a INNER JOIN
     (SELECT s.Opponent, SUM(s.QTY) as SQty
      FROM Stubhub.Sold s
      GROUP BY s.Opponent
     ) s
     ON a.Opponent = s.Opponent;

请注意,在这种情况下,您不需要外部查询中的聚合。