我有两张桌子。

a)ai_account



b)ai_order_product



我想对特定的vendor_id做一些计算。


  1,totalAmount,我想做类似的事情
  SUM(ai_order_product.quantity * ai_order_product.cost)
  
  2,amountPaid,这是供应商将支付的总金额
  类似于SUM(ai_account.amount),并引用了vendor_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获取一行。

附言:我刚刚输入了一些虚拟值,这就是为什么计算结果大多为负数,而在应用中计算值将为正数的原因。

最佳答案

那是因为对每个“ ai_order_product”行都进行了多次计数(ai_account表中的每一行一次)。

尝试这个:

SELECT
  op.totalAmount as totalAmount
  , SUM(ac.amount) as amountPaid
  , op.totalAmount - SUM(ac.amount) as balance
  , MAX(ac.addDate) as lastPayment
FROM (
  select supplier_id, sum(quantity * cost) as totalAmount
  from ai_order_product
  group by supplier_id) op
LEFT JOIN ai_account ac ON (op.supplier_id = ac.trader_id)
WHERE op.supplier_id = 42


这可能会稍微有些偏离,但是这种通用逻辑应该起作用。

关于mysql - 使用SUM计算,查询不起作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8168929/

10-16 15:49