我试图按发票金额和发票金额之和订购客户。为了获得发票的价值,我需要对可以(或不可以)在2个表格中的项目进行汇总:产品和支持。结构是这样的:
我尝试了此查询,但不起作用:
SELECT
c.id,
c.name,
COUNT(i.id) as total_amount,
SUM(ip.value * ip.quantity) as total_products,
SUM(sp.value) as total_support
FROM InVoice i
INNER JOIN Costumer c ON i.id_costumer = c.id
LEFT JOIN InVoice_Product ip ON ip.id_invoice = i.id
LEFT JOIN InVoice_Support sp ON sp.id_invoice = i.id
GROUP BY c.id, c.name
ORDER BY total_amount, total_products DESC
如果我在没有LEFT JOINS的情况下执行查询,仅查找发票金额,效果很好。。但是当我尝试添加JOINS时,结果与实际情况不符。
我对此感到困惑。
编辑:
以预期的结果(总计)为准:http://sqlfiddle.com/#!9/f001a7/4
答案 0 :(得分:1)
我认为您必须使用DISTINCT计数,并对产品和支持的总和求和。
SELECT
c.id,
c.name,
COUNT(DISTINCT i.id) as invoices_count,
SUM(ip.value * ip.quantity) + SUM(is.value) as total_amount
FROM Invoice i
INNER JOIN Costumer c ON i.id_costumer = c.id
LEFT JOIN InVoice_Product ip ON ip.id_invoice = i.id
LEFT JOIN InVoice_Support sp ON sp.id_invoice = i.id
GROUP BY c.id, c.name
ORDER BY invoices_count, total_amount DESC
尝试一下
答案 1 :(得分:0)
我认为问题在于对可能为空的值进行数学运算。试试看:
SELECT
c.id,
c.name,
COUNT(i.id) as total_amount,
SUM(IF(NOT ip.value IS NULL,ip.value * ip.quantity,0)) as total_products,
SUM(IF(NOT is.value IS NULL,is.value,0)) as total_support
FROM Invoice i
INNER JOIN Costumer c ON i.id_costumer = c.id
LEFT JOIN InVoice_Product ip ON ip.id_invoice = i.id
LEFT JOIN InVoice_Support sp ON sp.id_invoice = i.id
GROUP BY c.id, c.name
ORDER BY total_amount, total_products DESC
答案 2 :(得分:0)
只需“联合”两个表以及invoice_product和invoice_support,因为当前查询会在所有三个表(invoice,invoice_product,invoice_support)中找到相同的invoice_id:
select c.id, c.name, count (inv_prod_support.id_invoice), sum(inv_prod_support*quantity) as total_products,
sum(inv_prod_support.value) as total_support from
(select id_invoice, value, 0 as quantity from invoice_support
union select id_invoice, value, quantity from invoice_product ) inv_prod_support, invoice i
inner join customer c on i.id_customer = c.id
inner join inv_prod_support on inv_prod_support.id_invoice = i.id_invoice
group by c.id, c.name
order by total_amount, total_products desc