用于计算每个客户的订单数量和总美元金额的SQL查询

时间:2012-12-10 19:48:54

标签: sql ms-access

我有两张桌子 Order列:

OrderID,OrderDate,CID,EmployeeID

OrderItem列:

OrderID,ItemID,Quantity,SalePrice

我需要返回所有订单的CustomerID(CID),每个客户的订单数量以及每个客户的总金额。

到目前为止,我有两个单独的查询。一个给了我客户订单的数量......

SELECT CID, Count(Order.OrderID) AS TotalOrders
FROM [Order]
Where CID = CID 
GROUP BY CID
Order BY Count(Order.OrderID) DESC;

另一个给了我总销量。我在组合它们时遇到了麻烦...

SELECT CID, Sum(OrderItem.Quantity*OrderItem.SalePrice) AS TotalDollarAmount
FROM OrderItem, [Order]
WHERE OrderItem.OrderID = [Order].OrderID
GROUP BY CID

我在Access 2010中这样做。

2 个答案:

答案 0 :(得分:2)

创建一个查询,使用您现有的2个查询作为子查询,并加入CID上的2个子查询。在父查询中而不是在子查询中定义ORDER BY

SELECT
    sub1.CID,
    sub1.TotalOrders,
    sub2.TotalDollarAmount
FROM
    (
        SELECT
            CID,
            Count(Order.OrderID) AS TotalOrders
        FROM [Order]
        GROUP BY CID
    ) AS sub1
    INNER JOIN
    (
        SELECT
            CID,
            Sum(OrderItem.Quantity*OrderItem.SalePrice)
                AS TotalDollarAmount
        FROM OrderItem INNER JOIN [Order]
        ON OrderItem.OrderID = [Order].OrderID
        GROUP BY CID
    ) AS sub2
    ON sub1.CID = sub2.CID
ORDER BY sub1.TotalOrders DESC;

答案 1 :(得分:1)

您可以在其他SQL引擎中使用COUNT(DISTINCT ...)

SELECT CID, 
       Count(DISTINCT O.OrderID) AS TotalOrders, 
       Sum(OI.Quantity*OI.SalePrice) AS TotalDollarAmount 
FROM [Order] O
INNER JOIN [OrderItem] OI
  ON O.OrderID = OI.OrderID
GROUP BY CID 
Order BY Count(DISTINCT O.OrderID) DESC

遗憾的是,哪个Access不支持。相反,您可以先获取订单金额,然后在计算订单数量之前加入它们:

SELECT CID,
       COUNT(Orders.OrderID) AS TotalOrders,
       SUM(OrderAmounts.DollarAmount) AS TotalDollarAmount
FROM [Orders]
INNER JOIN (SELECT OrderID, Sum(Quantity*SalePrice) AS DollarAmount 
      FROM OrderItems GROUP BY OrderID) AS OrderAmounts
  ON Orders.OrderID = OrderAmounts.OrderID
GROUP BY CID
ORDER BY Count(Orders.OrderID) DESC

如果您需要包含订单中没有商品(不寻常但可能)的客户,请将INNER JOIN更改为LEFT OUTER JOIN