带联接和求和的SQL查询

时间:2019-04-18 20:47:43

标签: mysql join sum

我想获取所有发票总数的总和以及订购的所有物品的总和(按数量)。当我添加联接时,总和是错误的,似乎事情被计算为两倍。

我该如何解决?

select
sum(invoices_items.item_quantity) as registration_count,
sum(invoices.total_incl_vat) as registration_price
from  invoices
inner join invoices_items on invoices_items.invoice_id = invoices.id; 

3 个答案:

答案 0 :(得分:3)

当您加入发票的每一行时,结果中的行与项目中的行一样多。这将导致发票的总额增加。

如果您只想将两笔总和排成一行,则可以使用SELECT,而无需使用FROM子句和子查询。

SELECT (SELECT sum(item_quantity)
               FROM invoice_items) registration_count,
       (SELECT sum(total_incl_vat)
               FROM invoices) registration_price;

答案 1 :(得分:0)

看来发票项目有多于一项针对发票的记录 这样你就可以做到

select
invoices.id,
(select sum(invoices_items.item_quantity from invoices_items where invoices_items.invoice_id = invoices.id) as registration_count,
sum(invoices.total_incl_vat) as registration_price
from  invoices
group by invoices.id

答案 2 :(得分:0)

采用这种方法,您需要先进行汇总,然后再进行JOIN

SELECT  t.id, registration_price, registration_count
FROM 
(SELECT id, SUM(invoices.total_incl_vat) AS registration_price FROM invoices GROUP BY id) t
INNER JOIN
(SELECT  invoices_id, SUM(invoices_items.item_quantity AS registration_count FROM invoices_items GROUP BY invoices_id) tt 
ON tt.invoices_id = t.id
GROUP BY t.id WITH ROLLUP;