我有3个表需要加入,即表发票,商品和付款。表商品和付款表格将根据发票ID
加入表格发票现在,我需要按发票日期获得销售额,销售成本 付款 SUM 。
所以这是我的查询
SELECT SUM((I.price * qty) - (I.price * qty * discount)) as totalSales,SUM((I.price * qty) - (I.price * qty * discount)-costItem) as salesAfterCost, SUM(PAY.amount) as paymentReceived
FROM tbl_inv B LEFT JOIN tbl_item I ON B.id = I.id_invoice
LEFT JOIN tbl_payment PAY ON B.id = PAY.id_invoice
WHERE B.dateInv = '2013-04-01'
GROUP BY B.id,b.dateInv;
结果会像这样返回
totalSales salesAfterCost paymentReceived
75.540000 67.540000 622.8000
但是当我查看此查询以获取总付款时,它将返回不同的值。
SELECT SUM(PAY.amount) paymentReceived
FROM tbl_inv B LEFT JOIN tbl_payment PAY ON B.id = PAY.id_invoice
WHERE B.dateInv = '2013-04-01';
结果:
paymentReceived
155.7000
查询销售
SELECT SUM((I.price * qty) - (I.price * qty * discount)) as totalSales,SUM((I.price * qty) - (I.price * qty * discount)-costItem) as salesAfterCost
FROM tbl_inv B LEFT JOIN tbl_item I ON B.id = I.id_invoice
WHERE B.dateInv = '2013-04-01';
结果:
totalSales salesAfterCost
37.770000 33.770000
我该如何解决这个问题?
答案 0 :(得分:4)
将SUM()
移动到子查询中 - 此时,付款的每一行都与发票中的每一行匹配,从而产生笛卡尔联接
SELECT I.totalSales,I.salesAfterCost, PAY.paymentReceived
FROM tbl_inv B
LEFT JOIN (
select id_invoice,SUM((I.price * qty) - (I.price * qty * discount)) as totalSales,
SUM((I.price * qty) - (I.price * qty * discount)-costItem) as salesAfterCost
from tbl_item group by id_invoice) I
ON
B.id = I.id_invoice
LEFT JOIN (
select id_invoice,SUM(amount) as paymentReceived
from tbl_payment group by id_invoice) PAY
ON
B.id = PAY.id_invoice
WHERE B.dateInv = '2013-04-01'