SQL - 使用附加条件筛选查询结果

时间:2015-07-23 14:40:15

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

我有一个包含两个表的数据库:   - 记录我必须收到的所有付款的信用   - 记录我收到的付款的付款

结构是 信用:id,总计 付款方式:ID,已收到

我的目标是创建一个查询,打印尚未全额付款的所有付款。现在我写了一个成功打印的查询 - 信用额度 - 总金额请求 - 收到的总金额 我只需要添加一个条件:不要打印完全付款的记录。这是我的SQL代码:

SELECT Credit.id,
       Credit.total,
       (SELECT SUM(Payment.received)
       FROM Payment WHERE Payment.id = Credit.id) AS TotalReceived
FROM Credit
WHERE Credit.total > 0;

我尝试使用" WHERE Credit.total>更改最后一行TotalReceived"但它不起作用。

你可以帮帮我吗? :)

PS。在Credit中,id是唯一的,而在Payment表中可以出现许多具有相同id的行。

2 个答案:

答案 0 :(得分:3)

除非使用SubQueries,否则无法为聚合列添加WHERE子句。您必须使用GROUP BYHAVING

的组合

您的查询可以像这样重写(我更喜欢使用JOIN这种结构,而不是像您使用的那样使用与共同相关的查询。

SELECT Credit.id, Sum (Credit.total), SUM(Payment.received) TotalReceived
FROM Credit
INNER JOIN Payment ON Payment.id = Credit.id
WHERE Credit.total > 0
GROUP BY Credit.id

现在,添加一个HAVING子句

SELECT Credit.id, Sum (Credit.total), SUM(Payment.received) TotalReceived
FROM Credit
INNER JOIN Payment ON Payment.id = Credit.id
WHERE Credit.total > 0
GROUP BY Credit.id
HAVING SUM(Payment.received) > 0

如果您想要保留结构,请使用像这样的子查询

Select Id, Total, TotalReceived
From
(
    SELECT Credit.id, Credit.total, (SELECT SUM(Payment.received)
    FROM Payment WHERE Payment.id = Credit.id) AS TotalReceived
    FROM Credit
    WHERE Credit.total > 0
) DerivedTable
Where TotalReceived > 0

答案 1 :(得分:0)

这可以为您提供尚未支付的信用记录。您的付款表可能应该有一个creditId字段来加入,而不是Credit.id = Payment.id,但如果这是设置的,那么这应该有效。

SELECT  c.id,
        c.total,
        SUM(Nz(p.received,0)) AS totalreceived
FROM    Credit c
        LEFT JOIN Payment p ON c.id = p.id --not sure about this?
WHERE   c.total > 0
GROUP BY c.id, c.total
HAVING  c.total > SUM(Nz(p.received,0))