我有两张 table
Bills
:id amount reference
Transactions
:id 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
但是,这会为所有行返回相同的paid 值!我究竟做错了什么 ?
最佳答案
使用左连接而不是子查询:
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
关于sql - 选择总和和内连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15040414/