我的项目是关于一家珠宝店,我试图找到每个产品类别的利润。让我更具体
我有 3 张桌子可以提供信息:
SALES(salesid,productid,数量,价格)
salesid productid Quantity Price
11001 13001 4 5
11002 13002 6 10
11003 13003 5 16
.
.
11012 13012 7 15
RETURN(salesid,productid,日期,数量,价格)
salesid productid Quantity Price
11003 13003 1 16
11007 13007 3 12
11008 13008 3 8
PROCUREMENT(procurementid,productid,数量,价格)
procurementid productid Quantity Price
100001 13001 10 2
100002 13002 10 2
.
.
100012 13012 10 2
product_category(categoryid,category)
categoryid category
1 Gold
2 Silver
.
5 Platin
产品(Productid,categoryid)
Productid categoryid
13001 1
13002 3
.
.
13010 5
利润来自这种类型:
Profit=Quantity*Price(Sell)-Quantity*Price(Return)-Quantity*Price(Procurement)
现在问题来了..到目前为止我想到了这个
SELECT categoryid,
category,
(coalesce(a.rev,0)- coalesce(b.ret,0),
coalesce(c.cost,0)) AS profit
FROM product category AS g
JOIN product AS h ON g.categoryid = h.categoryid
JOIN
(SELECT categoryid,
sum(quantity*price) AS rev
FROM sales AS a,
product AS b
WHERE a.productid = b.productid
GROUP BY categoryid) a
LEFT OUTER JOIN
(SELECT cartegoryid,
sum(quantity*price) AS ret
FROM RETURN AS a ,
product AS b
WHERE a.productid = b.productid
GROUP BY categoryid) b ON a.categoryid = b.categoryid
LEFT OUTER JOIN
(SELECT categoryid,
sum(quantity*price) AS cost
FROM procurement AS a,
product AS b
WHERE a.productid = b.productid
GROUP BY categoryid) c ON a.categoryid = c.categoryid ,
product AS d,
procurement AS e
WHERE MONTH(f.date) = MONTH(e.date)
AND YEAR(date) = 2013
[抱歉对齐,我是该网站的新手,不知道如何很好地复制粘贴代码(:D)]当我这样做时,它会进入类似的状态
categoryid category profit
1 Gold -100
2 Silver -100
.
5 Platin -100
不知道问题出在哪里...我做了很多更改和切换,但没有任何结果...任何建议都会很有帮助。谢谢你