我的查询从2个子表中返回错误的2列总和,我在Google上搜索,也查看了关于Stackoverflow的建议,但它们从未起作用。
si_invoices
-----------------------------
id, date
1, 2014-05-07
si_invoice_items
-----------------------------
id, invoice_id, date , total
1, 100, 2014-05-07, 200
2, 100, 2014-05-07, 200
si_payment
-----------------------------
id, ac_inv_id, date , payment
1, 100, 2014-05-07, 100
2, 100, 2014-05-07, 200
SELECT SI.*,SUM(SII.total) as total,SUM(SIP.payment) as payment FROM
(SELECT * FROM si_invoices GROUP BY si_invoices.id) AS SI
LEFT JOIN si_invoice_items SII ON SII.invoice_id = SI.id
LEFT JOIN si_payment SIP ON SIP.ac_inv_id = SII.invoice_id
GROUP BY SI.id
在SQL中,它应该为字段‘TOTAL’返回400 SUM,但它返回800,与‘Payment’相同。你能指出我的问题中有什么错误吗?请帮帮忙,谢谢。
谢谢M.S.
3条答案
按热度按时间xmd2e60i1#
直接使用总计,因为您的联接可能会以您想要的组合方式创建更多行。
尝试以下操作:
或者,如果id是唯一的:
zzwlnbp82#
详细结果:
最终查询:
结果:
iyr7buue3#
选择
projects
.*,sum(project_tasks.ts_mount)作为Cost_Expend,sum(work_entries.w_mount)作为Actual_Amount fromprojects
左侧加入project_costs
上的project_costs
。proj_id
=projects
。proj_id
左加入project_costs
上的project_tasks
。cost_id
=project_tasks
。cost_id
左加入project_costs
上的work_entries
。cost_id
=work_entries
。cost_id
和work_entries
。w_status
=projects
的‘已批准’组。proj_id
;