[英]Get SUM of two fields in 2 different related tables
I'd like to get the SUM of the amount
column in two related tables. 我想获取两个相关表中的“
amount
列的总和。
Invoices Table: 发票表:
-----------------------------------------
| id | student_id | created | updated |
-----------------------------------------
| 5 | 25 | date | date |
-----------------------------------------
Invoice Items Table: 发票项目表:
------------------------------
| id | invoice_id | amount |
------------------------------
| 1 | 5 | 250 |
------------------------------
| 2 | 5 | 100 |
------------------------------
| 3 | 5 | 40 |
------------------------------
Payments Table: 付款表:
------------------------------
| id | invoice_id | amount |
------------------------------
| 1 | 5 | 100 |
------------------------------
| 2 | 5 | 290 |
------------------------------
Desired Output: 所需输出:
--------------------------------------
| id | invoiceTotal | paymentTotal |
--------------------------------------
| 1 | 390 | 390 |
--------------------------------------
The query I've tried 我尝试过的查询
SELECT
i.id,
sum(ii.amount) as invoiceTotal,
sum(p.amount) as paymentTotal
FROM
invoices i
LEFT JOIN
invoice_items ii ON i.id = ii.invoice_id
LEFT JOIN
payments p ON i.id = p.invoice_id
WHERE
i.student_id = '25'
GROUP BY
i.id
What this seems to do is calculate the sum of the payments properly but the invoice_items.amount
appears to have been duplicated by 6 (which is the number of payments
there are). 这似乎是在正确计算付款总和,但是
invoice_items.amount
似乎已被6重复(这是payments
的数量)。
I have read similar questions on SO here and here but the examples are so much more complex than what I'm trying to do and I can't figure out what to put where. 我在这里和这里都读过类似的问题,但示例比我要尝试的要复杂得多,我无法弄清楚该放在哪里。
The join causes a problem with cartesian products. 联接导致笛卡尔积的问题。 If a student has multiple invoice items and payments, then the totals will be wrong.
如果学生有多个发票项目和付款,则总数将是错误的。
One approach that works best for all invoices is a union all
/ group by
approach: 一种方法最适合所有发票是
union all
/ group by
的方法:
select i.id, sum(invoiceTotal) as invoiceTotal, sum(paymentTotal) as paymentTotal
from ((select i.id, 0 as invoiceTotal, 0 as paymentTotal
from invoices i
) union all
(select ii.invoiceId, sum(ii.amount) as invoiceTotal, NULL
from invoiceitems ii
group by ii.invoiceId
) union all
(select p.invoiceId, 0, sum(p.amount) as paymentTotal
from payments p
group by p.invoiceId
)
) iip
group by id;
For a single student, I would recommend correlated subqueries: 对于一个学生,我建议相关的子查询:
select i.id,
(select sum(ii.amount)
from invoiceitems ii
where ii.invoiceid = i.id
) as totalAmount,
(select sum(p.amount)
from payment p
where p.invoiceid = i.id
) as paymentAmount
from invoices i
where i.studentid = 25;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.