13

我有两张桌子

  • Billsid amount reference

  • Transactionsid reference amount

以下 SQL 查询

SELECT 
   *,
   (SELECT SUM(amount) 
    FROM transactions 
    WHERE transactions.reference = bils.reference) AS paid
FROM bills
GROUP BY id HAVING paid<amount

用于 table 中的某些行Bills,添加一个paid包含相关交易金额总和的列。

但是,它仅在每张账单至少有一笔交易时才有效。否则,不返回无交易账单行。

可能,那是因为我应该进行内部连接!

所以我尝试以下方法:

SELECT 
   *,
   (SELECT SUM(transactions.amount) 
    FROM transactions 
    INNER JOIN bills ON transactions.reference = bills.reference) AS paid
FROM bills
GROUP BY id 
HAVING paid < amount

但是,这会为所有行返回相同的支付值!我究竟做错了什么 ?

4

3 回答 3

22

使用左连接而不是子查询:

select b.id, b.amount, b.paid, sum(t.amount) as transactionamount
from bills b
left join transactions t on t.reference = b.reference
group by b.id, b.amount, b.paid
having b.paid < b.amount

编辑:
要将交易总和与金额进行比较,请处理没有交易时获得的空值:

having isnull(sum(t.amount), 0) < b.amount
于 2013-02-23T12:23:45.807 回答
2

您需要RIGHT JOIN包含所有账单行。

编辑 所以最终的查询将是

SELECT 
   *,
   (SELECT SUM(transactions.amount) 
    FROM transactions 
    WHERE transactions.reference = bills.reference) AS paid
FROM bills
WHERE paid < amount
于 2013-02-23T12:16:24.223 回答
0

我知道这个线程很旧,但我今天来到这里是因为我遇到了同样的问题。

请参阅另一篇具有相同问题的帖子: Sum on a left join SQL

正如答案所说,在左表上使用 GROUP BY 。这样您就可以从左表中获取所有记录,并将右表中的相应行求和。

尝试使用这个:

SELECT
   *,
  SUM(transactions.sum)
FROM
   bills
RIGHT JOIN
   transactions
ON
   bills.reference = transactions.reference
WHERE
   transactions.sum > 0
GROUP BY
   bills.id
于 2016-07-08T08:29:10.710 回答