0

这是我到目前为止所拥有的,但结果是错误的。

SELECT c.CompanyName,
       COUNT(o.OrderID) AS [Total Orders],
       SUM(
           (od.UnitPrice -
           (od.UnitPrice * od.Discount))* Quantity) AS [Purchase Total]
FROM Customers AS c,
     Orders AS o,
     [Order Details] AS od
WHERE c.CustomerID = o.CustomerID
AND o.OrderID = od.OrderID
GROUP BY c.CompanyName
ORDER BY c.CompanyName;

我遇到的问题是计数,它减少了两倍或更多。我相信这是因为 OrderID 多次出现在 Order Details 表中。我想我需要一个嵌套的 SELECT 语句,但我不确定该怎么做。

我会从第一个查询中删除 SUM() 表达式、订单详细信息和 AND 子句吗?还是我走远了?

在帮助下,我已经让 COUNT 字段工作,但现在我的 SUM 字段是错误的。这是我最近的尝试,它为每个客户产生了相同的价值。

SELECT c.CompanyName, 
       COUNT(o.OrderID) AS [Total Orders], 
        (SELECT SUM(
         (odIN.UnitPrice -
         (odIN.UnitPrice * odIN.Discount)) * odIN.Quantity) AS [OrderTotal]
         FROM [Order Details] AS odIN, Orders As oIN
         WHERE odIN.OrderID = oIN.OrderID) AS [Purchase Total]
FROM 
     Customers AS c, Orders AS o
WHERE c.CustomerID = o.CustomerID
GROUP BY c.CompanyName
ORDER BY c.CompanyName;

我无法让查询完全按照我想要的方式工作。然后我意识到也许我在寻找错误的数据。所以我将 COUNT 字段的名称更改为 Num Products Purchased。

我仍然希望以另一种方式工作,但我认为这将需要创建一个临时表或视图,可用于执行其中一个计算,然后从查询中调用它。这是我必须弄清楚的事情。

感谢您尝试提供帮助。

4

3 回答 3

1

因为 Access 没有,所以COUNT(DISTINCT)你需要创建一个内部查询。

这样做是在内部查询中计算订单中每个项目的总和,然后将客户的所有订单总和作为购买总和。一个单独的 OrderID 不会被计算两次,因为o现在od有一对一的关系。

某处可能存在语法错误,但这个想法应该可行。

SELECT c.CompanyName, 
       COUNT(o.OrderID) AS [Total Orders], 
       SUM(od.OrderTotal) AS [Purchase Total]
FROM 
     Customers AS c, 
     Orders AS o,
     (SELECT odIn.OrderID, 
         SUM(
         (odIn.UnitPrice -
         (odIn.UnitPrice * odIn.Discount)) * odIn.Quantity) AS [OrderTotal]
         FROM [Order Details] AS odIn
         GROUP BY odIn.OrderID) AS od
WHERE c.CustomerID = o.CustomerID
    AND o.OrderID = od.OrderID
GROUP BY c.CompanyName
ORDER BY c.CompanyName;
于 2013-09-12T23:58:17.983 回答
0

首先,我要感谢丹尼尔的帮助。我终于在另一个来源的帮助下得到了查询。Daniel 的解决方案更好,因为它需要的代码更少,甚至可以用货币格式化总和。

这是我要工作的那个:

SELECT vtOrdCnt.*, ROUND(vtTotCost.PurchaseTotal, 2) AS [Purchase Total]
FROM
(
SELECT CustomerID, COUNT(OrderID) AS TotalOrders
FROM orders
GROUP BY CustomerID
) AS vtOrdCnt,
(
SELECT CustomerID, SUM(UnitPrice * (1-Discount)*Quantity) AS PurchaseTotal
FROM Orders AS o, [Order Details] AS od
WHERE o.orderID = od.orderID
GROUP BY CustomerID
) AS vtTotCost
WHERE vtOrdCnt.CustomerID = vtTotCost.CustomerID
ORDER BY  vtOrdCnt.CustomerId

通过在 FROM 子句中使用别名和两个 select 语句,它允许查询按我想要的方式运行。

于 2013-09-13T03:52:22.377 回答
0

如果问题是因为 OrderID 出现多次,请尝试:

SELECT c.CompanyName, COUNT(DISTINCT o.OrderID) AS [Total Orders], SUM((od.UnitPrice - (od.UnitPrice * od.Discount)) * Quantity) AS [Purchase Total]
FROM Customers AS c, Orders AS o, [Order Details] AS od
WHERE c.CustomerID = o.CustomerID AND o.OrderID = od.OrderID
GROUP BY c.CompanyName
ORDER BY c.CompanyName;

distinct 子句让您只计算每次出现。

于 2013-09-12T23:58:55.997 回答