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

时间:2017-04-09 21:01:59

标签: mysql subquery

我正在尝试为所有订单返回每个客户的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
;

1 个答案:

答案 0 :(得分:1)

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