如果有一行使用Sum()函数,则Query不会显示结果

时间:2011-12-03 01:40:12

标签: sql ms-access ms-access-2010

我正在尝试创建一个Office Access程序来监控我的depts。

我有一张表格,其中包含了我对名为tbl_depts的人的欠款。

我有另一张表格,其中包含名为tbl_payments的付款。

这是我的语法:

SELECT DISTINCTROW
    tbl_depts.who,
    tbl_depts.dept,
    Sum(tbl_payments.payment) AS [Paid],
    (tbl_depts.dept - [Paid]) AS remaining
FROM tbl_depts INNER JOIN tbl_payments ON tbl_depts.[ID] = tbl_payments.[dept_ID]
GROUP BY tbl_depts.who;

但是有一个问题。如果部门只有一笔付款,则查询显示为空。但是,如果该部门有两笔付款,则此查询非常有效。

我该怎么办?

2 个答案:

答案 0 :(得分:0)

您的上述查询甚至无法运行 - 分组错误。 这有效:

SELECT tbl_depts.ID, tbl_depts.who, tbl_depts.dept, Sum(tbl_payments.payment) AS paid, [dept]-[payment] AS remaining
FROM tbl_payments INNER JOIN tbl_depts ON tbl_payments.dept_ID = tbl_depts.ID
GROUP BY tbl_depts.ID, tbl_depts.who, tbl_depts.dept, [dept]-[payment];

答案 1 :(得分:0)

使用 LEFT JOIN 时,如果使用 INNER JOIN ,请确保两个表都存在 dept_ID

SELECT DISTINCTROW
    tbl_depts.who,
    tbl_depts.dept,
    Sum(tbl_payments.payment) AS [Paid],
    (tbl_depts.dept - [Paid]) AS remaining
FROM tbl_depts LEFT JOIN tbl_payments 
     ON tbl_depts.[ID] = tbl_payments.[dept_ID]
GROUP BY tbl_depts.who, tbl_depts.dept, (tbl_depts.dept - [Paid]);