Mysql 按发票金额和项目总数订购客户
我试图根据发票金额和发票价值的总和来订购我的客户。要获得发票的价值,我需要对两个表中的项目进行合计:产品和支持。结构是这样的: 我尝试了此查询,但不起作用:Mysql 按发票金额和项目总数订购客户,mysql,sql,database,Mysql,Sql,Database,我试图根据发票金额和发票价值的总和来订购我的客户。要获得发票的价值,我需要对两个表中的项目进行合计:产品和支持。结构是这样的: 我尝试了此查询,但不起作用: 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 INN
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
如果我执行查询时没有左连接,只查找发票金额,效果很好。。但是当我尝试添加连接时,结果与实际不符
我在这件事上被绊倒了
编辑:
篡改预期结果(总金额):
处理完整的查询:我认为您必须使用不同的计数,并对产品和支持的总和进行求和
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
试一试我认为问题在于对可能为空的值进行数学运算。尝试一下:
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
只需“联合”两个表和发票\产品和发票\支持,因为当前查询发现发票\ id在所有三个表(发票、发票\产品、发票\支持)中通用:
你能提供一些示例数据和预期结果吗?如果你能分享sql fiddle,那就太遗憾了。。我编辑问题并分享结果。当查询包含联接和求和时,总金额会增加..我尝试。。total_支持和total_产品看起来不错,但total_金额不正确。。。工作!谢谢!:)
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