我有以下表格,作为MySQL Workbench 8.0CE中更大的架构的一部分;

订单-Order_ID,Customer_ID,Payment_ID,Delivery_ID,Order_Date,Cost_Price_Eur,Sales_Tax_Eur,
             欧元总价

退货-退货ID,订单ID,产品ID,付款ID,退货日期,Reason_for_Return,
              退货数量,退货价值_欧元

我正在尝试创建一个视图,以显示每月的累计销售额,收益和利润(销售额减去收益)。但是,我的脚本遇到了麻烦。我目前正在得到以下内容;

View

这里的问题是;

1)10月和11月虽然两个月都有订单和退货,但都没有进来。有趣的是,两个月的退货价值都超过订单的价值,因此这可能就是原因之一。

2)利润回报为0,而不是销售与回报之间的差。

我的脚本是当前;

Create view Trading_Summary as
SELECT
       a.Month_,
       ifnull(a.Sales_,0) as Sales,
       ifnull(b.Returns_,0) as Returns,
       ifnull(c.Profit_,0) as Profit
FROM
  (SELECT
   SUM(Total_Price_Eur) as Sales_, monthname(Order_Date) as Month_
   FROM orders
   GROUP BY Month_) a
INNER JOIN
  (SELECT
   SUM(Return_Value_Eur) as Returns_, monthname(Return_Date) as Month_
   FROM returns
   GROUP BY Month_) b
    on a.Month_ = b.Month_
INNER JOIN
   (SELECT
    SUM(Profit) as Profit_, Month_ FROM
    (SELECT
    orders.Total_Price_Eur-returns.Return_Value_Eur as Profit, monthname(orders.Order_Date) as Month_
    FROM orders
INNER JOIN
     returns ON
    orders.Order_ID = returns.Order_ID) B
  GROUP BY Month_) c on
     a.Month_ = c.Month_


任何帮助都会很棒。提前致谢。

最佳答案

可能是您不是每个月都尝试为您的表加入UNION

select t1.Month_, ifnull(a.Sales_,0), ifnull(b.Returns_,0),  ifnull(a.Sales_,0) - ifnull(b.Returns_,0) Profit
from (
  select  monthname(Order_Date) as Month_
  from orders
  UNION
  select  monthname(Order_Date)
  from returns
  ) t1
  LEFT JOIN (SELECT
   SUM(Total_Price_Eur) as Sales_, monthname(Order_Date) as Month_
   FROM orders
   GROUP BY Month_) a ON t1.Month_ = a.Month_
  LEFT JOIN (SELECT
     SUM(Return_Value_Eur) as Returns_, monthname(Return_Date) as Month_
     FROM returns
   GROUP BY Month_
  ) b ON ON t1.Month_ = b.Month_

关于mysql - 使用Join创建一个在MySQL中显示销售,退货和利润(销售额-退货)的 View ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59219703/

10-13 00:48