我的项目是关于一家珠宝店,我尝试找到利润最大的产品。
我有 3 个表格,其中提供了信息:
销售表:
salesid productid Quantity Price
11001 13001 4 5
11002 13002 6 10
11003 13003 5 16
.
.
11012 13012 7 15
返回表:
salesid productid Quantity Price
11003 13003 1 16
11007 13007 3 12
11008 13008 3 8
采购表:
procurementid productid Quantity Price
100001 13001 10 2
100002 13002 10 2
.
.
100012 13012 10 2
利润由以下公式给出:
Profit = Quantity * Price(Sell) - Quantity * Price(Return) - Quantity * Price(Procurement)
现在问题来了。到目前为止我已经想到了这一点
select a.productid,(a.quantity*a.price-b.quantity*b.price-c.quantity*c.price) as Profit
from sales as a ,return as b ,procurement as c
where a.productid = c.productid
GROUP BY productid
在这种情况下我没有得到正确的答案。
这是因为在返回表中我只有 3 个寄存器,但在其他表中我有 12 个寄存器,因此当它计算利润时,它会为其他表的每一行使用整个返回表。
我尝试使用max(Profit)
,但它没有做任何事情。
我实际上不知道如何连接返回表的3个寄存器,以便仅在必要时才使用它们。当我尝试连接时,很多行都是空的。我认为必须使用 OUTER JOIN 或其他方法来完成某些操作,但我不知道该怎么做。
最佳答案
您似乎对 SQL 相当陌生。给表别名时,尝试使用表缩写。它使查询更易于阅读(例如,p
表示 采购
,s
表示销售)。
此外,您还需要学习正确的连接语法。但是,这对您没有真正的帮助,因为您需要在进行连接之前进行预聚合。也就是说,分别获取成本、销售额和返回金额,然后将它们汇总在一起:
select p.productid,
(coalesce(s.rev, 0) - coalesce(r.ret, 0) - coalesce(p.cost, 0)) as profit
from (select p.productid, SUM(quantity*price) as cost
from procurement p
group by p.productid
) p left outer join
(select s.productid, sum(quantity*price) as rev
from sales s
group by s.productid
) s
on p.productid = s.productid
(select r.productid, sum(quantity*price) as ret
from return
group by s.productid
) r
on p.productid = r.productid;
此查询还使用左外连接
。这很重要,因为并非所有产品都可能有销售或返回。您不想仅仅因为它们是糟糕的卖家(没有销售)或非常受欢迎(没有返回)而失去这些。
关于mysql - 如何计算 3 个不同表格之间的利润,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16815212/