2017-04-09 61 views
-1

上使用子查詢我試圖爲每個客戶返回CustomerID,CompanyName,OrderID和小計以訂購小於客戶平均小計金額的小計金額。這些是我正在使用的表格和下面的查詢。我不確定我返回的價值是否正確,並且希望有人能夠幫助我瞭解他們是否基於我的查詢。提前致謝。MySQL - 在加入和

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 
; 
+0

你想要一些爲 「檢查代碼」?如果沒有錯誤/失敗,那麼問答不適合您的帖子。 – mickmackusa

回答

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