选择总和和内部联接

时间:2013-02-23 12:13:25

标签: sql join

我有两张桌子

  • 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

表示表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

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

3 个答案:

答案 0 :(得分:17)

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

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

答案 1 :(得分:2)

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

修改 所以最终的查询将是

SELECT 
   *,
   (SELECT SUM(transactions.amount) 
    FROM transactions 
    WHERE transactions.reference = bills.reference) AS paid
FROM bills
WHERE paid < amount

答案 2 :(得分: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