Access数据库为字段收入返回双SUM

时间:2011-02-23 14:31:44

标签: ms-access

我在access 2003 mdb中有以下查询。

SELECT Company.Name, Company.Address, Place.Name_of_Place, Sum(Income.Value) AS Income, Sum(Invoice.Value) AS Invoice 
FROM ((Company LEFT JOIN Invoice ON Company.CompanyID = Invoice.CompanyID) LEFT JOIN Income ON Company.CompanyID = Income.CompanyID) INNER JOIN Place ON 
Place.Postal = Company.Postal 
GROUP BY Company.Name, Company.Address, Place.Name_of_Place, Company.CompanyID
HAVING ((iif(IsNull(Sum(Invoice.Value)), 0, Sum(Invoice.Value)) - iif(IsNull(Sum(Income.Value)), 0, Sum(Income.Value))) > 0) 
ORDER BY Company.Name;

收入字段值为500,但查询返回1000。 必须存在具有这些Left连接的内容,才能对该Income表进行两次搜索。 怎么解决这个? 我想在我的程序中为这个专栏做2个简单的除法,但我更愿意在数据库级别解决这个问题。

此致

Vajda

1 个答案:

答案 0 :(得分:4)

当您使用发票加入公司时,结果将包含与发票中的行一样多的行。因此,如果公司有2张发票,您将拥有 2行

然后,当您加入收入时(我不确定每家公司有多少行),每行收入的结果将是2行

您将不得不诉诸子查询,如下所示:

SELECT
  Company.Name,
  Company.Address,
  Place.Name_of_Place,
  (SELECT SUM(Income.Value) FROM Income WHERE Income.CompanyID=Company.CompanyID) AS Income,
  (SELECT SUM(Invoice.Value) FROM Invoice WHERE Invoice.CompanyID=Company.CompanyID) AS Invoice
FROM
  Company INNER JOIN Place ON Place.Postal = Company.Postal
WHERE 
  Invoice - Income > 0
ORDER BY
  Company.Name;