左联接中的MySQL查询总和

时间:2019-03-28 14:15:43

标签: mysql

下面的查询在select和join两个表中使用SUM。 SUM的结果包括所有期间的金额。我怀疑这是由于SUM放置的位置。 我认为帖子here 包含我遇到的相同问题。我已尝试按照给出的解决方案进行操作,但似乎无法使其正常工作。

查询:

SELECT
  Mo911ZipLookup.X_STATE AS StateAbbr,
  Mo911ZipLookup.X_CITY AS City,
  Mo911ZipLookup.X_COUNTY AS County,
  SUM(SourceDataTCX.E911Amount) AS E911Amount,
  SourceDataTCX.period AS period
FROM (SourceDataTCX
  LEFT JOIN Mo911ZipLookup
    ON ((SourceDataTCX.ZipCode = Mo911ZipLookup.X_ZIPCODE)))
WHERE (Mo911ZipLookup.X_STATE = 'MO' AND SourceDataTCX.period = '2019-02-01')
GROUP BY Mo911ZipLookup.X_STATE,
         Mo911ZipLookup.X_CITY,
         Mo911ZipLookup.X_COUNTY,
         SourceDataTCX.period
ORDER BY Mo911ZipLookup.X_STATE, Mo911ZipLookup.X_COUNTY, Mo911ZipLookup.X_CITY

查询应仅返回2019-02-01期间的金额,但其中包括所有期间的金额。我认为应该将SUM移入联接。有人可以帮我吗?

编辑 查询产生的结果如下:

StateAbbr   City    County  E911Amount  period  
MO  BALLWIN SAINT LOUIS 614.80  2019-02-01
MO  ELLISVILLE  SAINT LOUIS 614.80  2019-02-01
MO  MANCHESTER  SAINT LOUIS 614.80  2019-02-01
MO  TWIN OAKS   SAINT LOUIS 614.80  2019-02-01
MO  WILDWOOD    SAINT LOUIS 614.80  2019-02-01
MO  WINCHESTER  SAINT LOUIS 614.80  2019-02-01

每个城市总计的金额显示为所有城市的总计。我认为SUM是在GROUP BY之前应用的。

1 个答案:

答案 0 :(得分:0)

将过滤器Mo911ZipLookup.X_STATE = 'MO'移至ON子句:

 SELECT Mo911ZipLookup.X_STATE AS StateAbbr,
   Mo911ZipLookup.X_CITY AS City,
   Mo911ZipLookup.X_COUNTY AS `County,,
   z.E911Amount,
   z.period AS period FROM
(
 SELECT SUM(E911Amount`) AS E911Amount,period AS period, ZipCode
 FROM SourceDataTCX
 WHERE period = '2019-02-01'
GROUP BY period, ZipCode      
) z
LEFT JOIN Mo911ZipLookup ON  z.ZipCode = Mo911ZipLookup.X_ZIPCODE
                      AND Mo911ZipLookup.X_STATE = 'MO' 
ORDER BY Mo911ZipLookup.X_STATE, Mo911ZipLookup.X_COUNTY, Mo911ZipLookup.X_CITY