5

我有两个 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 中执行此操作。

4

2 回答 2

2

您将COUNT(DISTINCT ...)在其他 SQL 引擎中使用:

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 JOINLEFT OUTER JOIN

于 2012-12-10T19:53:52.923 回答
2

创建一个使用您现有的 2 个查询作为子查询器的查询,并将 2 个子查询加入到CID. 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;
于 2012-12-10T20:06:53.177 回答