mysql - 如何计算 3 个不同表格之间的利润

标签 mysql sql max mysql-workbench

我的项目是关于一家珠宝店,我尝试找到利润最大的产品。

我有 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/

相关文章:

HIghcharts 4 固体规范最大值

max - 这对函数 floor()/ceil() 和 min()/max() 之间有什么区别?

mysql - 调整 MySQL 配置以支持锁定同一表的数百个连接

Mysql不选择空值

mysql - 让mysql查询更高效

sql - PostgreSQL:使用 join 和 group by 查询花费的时间太长

php - 如果我搜索确切的字符串,为什么 sql 查询不返回数据?

mysql - 比较最后两行值

sql - 在表格中选择不在特定范围内的值

python - 如何使用python查找列表中最大数字出现的次数?