MySQL-在join和from上使用子查询

MySQL-在join和from上使用子查询,mysql,subquery,Mysql,Subquery,我试图返回所有订单的CustomerID、CompanyName、OrderID和每个客户的小计,小计金额高于客户的平均小计金额。下面是我正在使用的表和查询。我不确定我返回的值是否正确,希望有人能帮助我了解它们是否基于我的查询。提前谢谢 Orders Columns OrderID CustomerID EmployeeID OrderDate RequiredDate OrderDetails Columns OrderID ProductID UnitP

我试图返回所有订单的CustomerID、CompanyName、OrderID和每个客户的小计,小计金额高于客户的平均小计金额。下面是我正在使用的表和查询。我不确定我返回的值是否正确,希望有人能帮助我了解它们是否基于我的查询。提前谢谢

Orders
 Columns
  OrderID
  CustomerID
  EmployeeID
  OrderDate
  RequiredDate

OrderDetails
 Columns
  OrderID
  ProductID
  UnitPrice
  Quantity

Products
 Columns
  ProductID
  ProductName
  QuantityPerUnit
  UnitPrice

Customers
 Columns
  CustomerID
  CompanyName
  ContactName
  Country





SELECT A.CustomerID, A.CompanyName, A.Subtotal, A.OrderID, AVGSubtotal
FROM (
    SELECT
        C.CustomerID,
        C.CompanyName,
        (D.UnitPrice * P.QuantityPerUnit) AS Subtotal,
        D.OrderID
    FROM Customers C
        JOIN Orders O ON C.CustomerID = O.CustomerID
        JOIN OrderDetails D ON D.OrderID = O.OrderID
        JOIN Products P ON P.ProductID = D.ProductID
    GROUP BY
        D.OrderID, C.CustomerID
) A
JOIN (
    SELECT
        S.CustomerID, S.CompanyName, AVG(S.Subtotal) as AVGSubtotal
    FROM (
        SELECT
            C.CustomerID,
            C.CompanyName,
            (D.UnitPrice * P.QuantityPerUnit) AS Subtotal
        FROM Customers C
            JOIN Orders O ON C.CustomerID = O.CustomerID
            JOIN OrderDetails D ON D.OrderID = O.OrderID
            JOIN Products P ON P.ProductID = D.ProductID
        GROUP BY
            D.OrderID, C.CustomerID
        ) S
    GROUP BY
        S.CustomerID
) B ON A.CustomerID = B.CustomerID 
WHERE
    A.CustomerID = B.CustomerID AND 
    A.Subtotal > B.AVGSubtotal 
ORDER BY
    A.CustomerID, A.CompanyName
;
你想要一些“检查你的代码”吗?如果没有错误/失败,那么问答就不是你发表文章的地方。
select
  c2.customerID,
  c2.CompanyName,
  c2.AVGSubtotal
  o2.OrderID,
  o2.UnitPrice * o2.Quantity as subtotal
from (
  select
    c.CustomerID,
    c.CompanyName,
    sum(o.UnitPrice * o.Quantity)/count(*) as AVGSubtotal
  from
    Customers c
    inner join Orders o on (o.CustomerID = c.CustomerID)
    inner join OrderDetails od on (od.OrderID = c.OrderID)
  group by
    o.CustomerID  
) as c2
inner join Orders o2 on (o2.CustomerID = c2.CustomerID)
where o2.UnitPrice * o2.Quantity > c2.AVGSubtotal