我一直致力于客户项目。我需要从已购买的产品数量和已售出的数量中获得库存。
这是我的SQL
SELECT DISTINCTROW tbl_itemmaster.product_code,tbl_itemmaster.unittype,tbl_itemmaster.color,SUM(tbl_purchasedetails.qty),SUM(tbl_saledetails.qty),(SUM(tbl_purchasedetails.qty)-SUM(tbl_saledetails.qty))
FROM (tbl_itemmaster LEFT JOIN tbl_saledetails ON tbl_itemmaster.[product_code] = tbl_saledetails.[product_code])
LEFT JOIN tbl_purchasedetails ON tbl_itemmaster.[product_code]=tbl_purchasedetails.[product_code] GROUP BY tbl_itemmaster.product_code,tbl_itemmaster.unittype,tbl_itemmaster.color
以下是sql的结果
-----------------------------------------------------------------
Product Code Unit Type Color Purchase QTY Sold QTY Stock
-----------------------------------------------------------------
1001 KiloGram Red 500
500 Kilogram White 1033 300 733
570 Kilogram Black
600 Kilogram Pink
9005 Kilogram Magenta 800.5
900 Kilogram Green
-----------------------------------------------------------------
产品代码 500 有三次购买条目,即500 + 400 + 133 = 1033购买数量
产品代码 500 只有一次销售条目,即100 = 100售出数量
产品代码 500 假设 933 库存数量
但为什么我卖出300的数量?
我的查询缺乏的地方?
请帮助!!!
答案 0 :(得分:0)
您正在购买笛卡尔产品,因为产品有多次销售和购买。
解决方案是在加入之前进行聚合:
SELECT im.product_code, im.unittype, im.color,
pd purchaseqty, sd.salesqty),
(purchaseqty - salesqty)
FROM (tbl_itemmaster as im LEFT JOIN
(SELECT product_code, SUM(qty) as salesqty
FROM tbl_saledetails
GROUP BY product_code
) as sd
ON im.[product_code] = sd.[product_code]
) LEFT JOIN
(SELECT product_code, SUM(qty) as purchaseqty
FROM tbl_purchasedetails
GROUP BY product_code
) as pd
ON im.[product_code] = pd.[product_code];