我有兩個表。使用SUM進行計算,查詢不起作用?
一) ai_account
B) ai_order_product
我想要做特定supplier_id一些計算。
1,總金額,我想這樣做 SUM(ai_order_product.quantity * ai_order_product.cost)
2,amountPaid,這是由供應商支付的總金額,這將是 像SUM (ai_account.amount)參考supplier_id。
3)平衡,這將通過SUM來計算(ai_order_product.quantity * ai_order_product.cost) - SUM(ai_invoice.amount)
4)lastPayment日期,這將是MAX(ai_account.addDate)。
我試着做這樣的事情。
SELECT SUM(op.quantity * op.cost) as totalAmount,
SUM(ac.amount) as amountPaid,
SUM(op.quantity * op.cost) - SUM(ac.amount) as balance,
MAX(ac.addDate) as lastPayment
FROM ai_order_product op
LEFT JOIN ai_account ac
ON (op.supplier_id = ac.trader_id)
WHERE op.supplier_id = 42
它不能正常工作,它獲取一些意想不到的值,而對於被預計上述結果是,
for supplier_id = 42,
1) totalAmount = 1375,
2) amountPaid = 7000,
3) balance = -5625,
4) lastPayment = 2011-11-23
and for supplier_id = 35,
1) totalAmount = 1500,
2) amountPaid = 43221,
3) balance = -41721,
4) lastPayment = 2011-11-28
and for supplier_id = 41
1) totalAmount = 0
2) amountPaid = 3000,
3) balance = -3000,
4) lastPayment = 2011-11-09
我想supplier_id獲取一行。
P.S:我剛剛輸入了一些虛擬值,這就是爲什麼計算大多是負值,而在應用中計算值是正值。
您的表格中沒有任何'trader_id' ... –
這是錯誤的,我將其更改爲supplier_id :) –
會發生什麼? – drdwilcox