mysql左连接在group by上返回错误的值

时间:2018-03-21 14:32:00

标签: mysql left-join

我遇到左派加入群组的问题。我的净率为336.83而实际只有25.91

SELECT L.EnquiryId,L.Levelcode, im.imcode, im.ItemName, im.ItemDescription, cs.conditionofsupply, rm.rawmaterial, L.Validity, ROUND(SUM(rmc.Netrate), 2), ROUND(SUM(cc.pc), 2) ,IFNULL (ROUND(SUM(Bc)),0)
FROM level1 L
LEFT JOIN (SELECT imcode,ItemName,ItemDescription,csid FROM Itemmaster)im
    ON (im.imcode=L.imcode)
LEFT JOIN (SELECT Id,conditionofsupply FROM csmaster)cs
    ON (cs.id=im.csid)
LEFT JOIN (SELECT rmcode,rawmaterial FROM rawmaterialmaster)rm
    ON (rm.rmcode=L.rmcode)
LEFT JOIN (SELECT Netrate,ScrapWeight*ScrapRate,GrossRate,CostingId,EnquiryId FROM rawmaterialcosting)rmc
    ON (L.EnquiryId=rmc.EnquiryId)  
LEFT JOIN (SELECT Mutlipleunit*Rate AS pc,CostingId,EnquiryId FROM Conversioncosting)cc
    ON (L.EnquiryId=cc.EnquiryId)  
LEFT JOIN (SELECT Numbers*Rate AS Bc,CostingId,EnquiryId FROM Boughtoutcosting)bc
    ON (L.EnquiryId=bc.EnquiryId)  
WHERE L.EnquiryId=5
GROUP BY rmc.CostingId,cc.CostingId,bc.CostingId
ORDER BY L.ID ASC

这有什么问题,请帮助。

1 个答案:

答案 0 :(得分:0)

您应该确保select子句中的所有非聚合字段都包含在group by子句中。所以试试这个:

SELECT rmc.CostingId,cc.CostingId,bc.CostingId, ROUND(SUM(rmc.Netrate), 2), ROUND(SUM(cc.pc), 2) ,IFNULL (ROUND(SUM(Bc)),0)
FROM level1 L
LEFT JOIN (SELECT imcode,ItemName,ItemDescription,csid FROM Itemmaster) im
    ON (im.imcode=L.imcode)
LEFT JOIN (SELECT Id,conditionofsupply FROM csmaster) cs
    ON (cs.id=im.csid)
LEFT JOIN (SELECT rmcode,rawmaterial FROM rawmaterialmaster) rm
    ON (rm.rmcode=L.rmcode)
LEFT JOIN (SELECT Netrate,ScrapWeight*ScrapRate,GrossRate,CostingId,EnquiryId FROM rawmaterialcosting) rmc
    ON (L.EnquiryId=rmc.EnquiryId)  
LEFT JOIN (SELECT Mutlipleunit*Rate AS pc,CostingId,EnquiryId FROM Conversioncosting) cc
    ON (L.EnquiryId=cc.EnquiryId)  
LEFT JOIN (SELECT Numbers*Rate AS Bc,CostingId,EnquiryId FROM Boughtoutcosting) bc
    ON (L.EnquiryId=bc.EnquiryId)  
WHERE L.EnquiryId=5
GROUP BY rmc.CostingId,cc.CostingId,bc.CostingId
ORDER BY L.ID ASC