结合MySQL查询会产生错误的答案

时间:2011-02-09 23:27:15

标签: mysql group-by sum

好的,所以我们为每个客户提供了大量的销售数据。我可以使用简单的查询轻松找到查询以获得每个销售代表的总销售量:

SELECT  `MerchantAddresses`.`Rep Number` AS `Rep Number`,
          SUM(`RESIDUALS_2010_12`.`Qual Cr Vol` + `RESIDUALS_2010_12`.`Qual Ch Vol`) AS `VOL_2010_12`,
          `Reps`.`First` AS `First`,
          `Reps`.`Last` AS `Last`
FROM     `MerchantAddresses`, `RESIDUALS_2010_12`, `Reps`
WHERE   `RESIDUALS_2010_12`.`MID` = `MerchantAddresses`.`MID` AND
          `Reps`.`ID` = `MerchantAddresses`.`Rep Number`
GROUP BY    `MerchantAddresses`.`Rep Number`
ORDER BY SUM(`RESIDUALS_2010_12`.`Qual Cr Vol` + `RESIDUALS_2010_12`.`Qual Ch Vol`) DESC

此代码完全正常,返回一个表,按销售代表分组一个月的总销售额。目前,我们已经运行了三个单独的查询来获取3个月的销售数据。我想将这三个查询合并为一个。

所以,我做了以下事情:

SELECT  `MerchantAddresses`.`Rep Number` AS `Rep Number`,
          SUM(`RESIDUALS_2010_12`.`Qual Cr Vol` + `RESIDUALS_2010_12`.`Qual Ch Vol`) AS `VOL_2010_12`,
          SUM(`RESIDUALS_2010_11`.`Qual Cr Vol` + `RESIDUALS_2010_11`.`Qual Ch Vol`) AS `VOL_2010_11`,
          SUM(`RESIDUALS_2010_10`.`Qual Cr Vol` + `RESIDUALS_2010_10`.`Qual Ch Vol`) AS `VOL_2010_10`,
          `Reps`.`First` AS `First`,
          `Reps`.`Last` AS `Last`
FROM     `MerchantAddresses`, `RESIDUALS_2010_12` JOIN ON `RESIDUALS_2010_11` JOIN ON `RESIDUALS_2010_10`, `Reps`
WHERE   `RESIDUALS_2010_12`.`MID` = `MerchantAddresses`.`MID` AND
          `RESIDUALS_2010_11`.`MID` = `MerchantAddresses`.`MID` AND
          `RESIDUALS_2010_10`.`MID` = `MerchantAddresses`.`MID` AND
          `Reps`.`ID` = `MerchantAddresses`.`Rep Number`
GROUP BY  `MerchantAddresses`.`Rep Number`
ORDER BY SUM(`RESIDUALS_2010_12`.`Qual Cr Vol` + `RESIDUALS_2010_12`.`Qual Ch Vol`) DESC

我发现我实际上使用此查询得到的值不正确。它有效,但我为每个销售代表获得的交易量实际上太小......

有什么想法吗?谢谢!

1 个答案:

答案 0 :(得分:1)

我认为你不能只是加入这些月度表,因为它们并没有真正相关。他们共享相同的商家地址,但就是这样。

使用UNION ALL,您可以组合多个查询的结果。这样,您就可以获得子查询中所有月度记录的值,并将它们汇总在父级中。

我冒昧地在你的查询中添加了一些别名。

SELECT
  m.`Rep Number`,
  SUM(m.vol10) as VOL_2010_10,
  SUM(m.vol11) as VOL_2010_11,
  SUM(m.vol12) as VOL_2010_12,
  m.First,
  m.Last
FROM  
  (
  SELECT  
    ma.`Rep Number`,
    r10.`Qual Cr Vol` + r10.`Qual Ch Vol` AS vol10,
    null as vol11,
    null as vol12
  FROM
    MerchantAddresses ma
    INNER JOIN RESIDUALS_2010_10 as r10 on r10.MID = ma.MID
  UNION ALL
  SELECT  
    ma.`Rep Number`,
    null as vol10,
    r11.`Qual Cr Vol` + r11.`Qual Ch Vol` AS vol11,
    null as vol12
  FROM
    MerchantAddresses ma
    INNER JOIN RESIDUALS_2010_11 as r11 on r11.MID = ma.MID
  UNION ALL 
  SELECT  
    ma.`Rep Number`,
    null as vol10,
    null as vol11,
    r12.`Qual Cr Vol` + r12.`Qual Ch Vol` AS vol12
  FROM
    MerchantAddresses ma
    INNER JOIN RESIDUALS_2010_12 as r12 on r12.MID = ma.MID
  ) m
  INNER JOIN Reps r ON r.ID = m.`Rep Number`
GROUP BY
  m.`Rep Number`
ORDER BY 
  SUM(m.vol12) DESC