我的项目是关于一家珠宝店,我试图找到每个产品类别的利润。 让我更具体一点
我有3张表给我提供信息:
SALES(salesid,产品ID,数量,价格)
salesid productid Quantity Price
11001 13001 4 5
11002 13002 6 10
11003 13003 5 16
.
.
11012 13012 7 15
RETURN(salesid,产品ID,日期,数量,价格)
salesid productid Quantity Price
11003 13003 1 16
11007 13007 3 12
11008 13008 3 8
采购(procurementid,产品ID,数量,价格)
procurementid productid Quantity Price
100001 13001 10 2
100002 13002 10 2
.
.
100012 13012 10 2
PRODUCT_CATEGORY(类别ID,类别)
categoryid category
1 Gold
2 Silver
.
5 Platin
产物(PRODUCTID,类别ID)
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)] wahtever,当我这样做它来到一个像
的状态categoryid category profit
1 Gold -100
2 Silver -100
.
5 Platin -100
不知道问题出在哪里...我做了很多改动和转换但没有任何结果......任何建议都会如此有用。谢谢你的推荐
答案 0 :(得分:0)
最初看起来您的利润公式中有一个额外的逗号。 此
(coalesce(a.rev,0) - coalesce(b.ret,0),coalesce(c.cost,0)) as profit
应该是这个
coalesce(a.rev,0) - coalesce(b.ret,0) - coalesce(c.cost,0) AS profit
此查询的几个问题
AND YEAR(date) = 2013
应为e.date
或f.date
。如果您尝试运行它,那应该会给您一个错误。WHERE MONTH(f.date) = MONTH(e.date)
哪个表是f.date指的?您没有为任何表格提供f
的别名。