按发票金额和项目总数订购客户

yzckvree  于 2021-06-21  发布在  Mysql
关注(0)|答案(3)|浏览(299)

我试着按发票金额和发票价值的总和来订购我的客户。为了得到发票的价值,我需要对两个表中的项目求和:产品和支持。结构如下:

我尝试了此查询,但不起作用:

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

如果我不使用左连接执行查询,只查找发票金额,效果很好。。但当我尝试添加连接时,结果与实际不符。。
我被这个绊住了。
编辑:
篡改预期结果(总额):http://sqlfiddle.com/#!9/f001a7/4号文件
摆弄完整的查询:http://sqlfiddle.com/#!9/f001a7/5号

z18hc3ub

z18hc3ub1#

只需“联合”两个表以及invoice\u product和invoice\u support,因为当前查询发现invoice\u id在所有三个表中都是通用的(invoice,invoice\u product,invoice\u support):

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
x7rlezfr

x7rlezfr2#

我认为你必须使用一个独特的计数,也总和产品和支持。

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

试试看

j13ufse2

j13ufse23#

我认为问题在于对可能为空的值进行数学运算。试一试:

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

相关问题