如何使用连接对查询中的所有行求和?
SELECT SUM(accounting.amount) AS sum, SUM(balance_invoice.amount) AS sum_balance
FROM accounting
LEFT JOIN balance_invoice ON balance_invoice.accounting_id=accounting.id
我需要此查询只返回一行,总和为accounting.amount
和balance_invoice.amount
可以将多行连接到每个accounting.id
SELECT SUM(accounting.currency_amount*-1 + (
SELECT SUM(balance_invoice_accounting.currency_amountoff)
FROM balance_invoice_accounting
WHERE balance_invoice_accounting.accounting_id=accounting.id
)) AS sum
FROM accounting
答案 0 :(得分:1)
只需在SUM()
- 函数中添加两个值:
SELECT SUM(accounting.amount + balance_invoice.amount) AS sum_all
FROM accounting
LEFT JOIN balance_invoice ON balance_invoice.accounting_id=accounting.id
如果其中一列可以是NULL
,则应添加其他COALESCE()
:
SELECT
SUM(COALESCE(accounting.amount,0) + COALESCE(balance_invoice.amount,0) AS sum_all
FROM accounting
LEFT JOIN balance_invoice ON balance_invoice.accounting_id=accounting.id
修改强>
对不起,我错过了那个重要的部分。如果您只想计算每accounting.amount
个balance_invoice.amount
,而且可以有多个SELECT
a.id,
(
a.amount
+
(SELECT SUM(b.amount) FROM balance_invoice b WHERE b.accounting_id = a.id)
) AS sum_all
FROM
accounting a
加入它,我会使用这样的子选择:
{{1}}