1
SELECT     
   ISNULL(Customer.Name, ' GRAND') AS CustomerName, 
   ISNULL(Item.ItemName, 'TOTAL') AS ItemName, 
   SUM(Item_Order.PriceAtDate) AS Price
FROM         
   Item_Order 
INNER JOIN
   Item ON Item_Order.ItemID = Item.ItemID 
INNER JOIN
   TheOrder ON Item_Order.OrderID = TheOrder.OrderID 
INNER JOIN
   Customer ON TheOrder.CustomerID = Customer.CustomerID
GROUP BY 
   Customer.Name, Item.ItemName, Item_Order.PriceAtDate WITH ROLLUP
ORDER BY 
   Customer.Name

结果:

CustomerName ItemName            Price
------------ ------------------- -------
GRAND        TOTAL               1380.46
Adrian       Hammer                21.88
Adrian       Hammer                21.88
Adrian       Soldering Iron        30.54
Adrian       Soldering Iron        30.54
Adrian       TOTAL                 52.42
Baker        Valve                 21.88
Baker        Valve                 21.88
Baker        TOTAL                 21.88

如您所见,使用汇总给出的 TOTAL 加起来为 30.54 和 21.88,即为 52.42,但这两个项目都订购了两次。所以我需要实际的总数,而不仅仅是不同的值。

有谁知道我做错了什么?

4

1 回答 1

0

我相信在你正在做总和的价格列(Item_Order.PriceAtDate)上进行分组会导致问题:

Customer.Name, Item.ItemName, Item_Order.PriceAtDate WITH ROLLUP

尝试改用子查询

SELECT
    ISNULL(CustomerName, ' GRAND') AS CustomerName, 
    ISNULL(ItemName, 'TOTAL') AS ItemName, 
    Sum(Price) AS Price
FROM
(
SELECT     
   Customer.Name AS CustomerName,
   Item.ItemName AS ItemName,   
   Item_Order.PriceAtDate AS Price
FROM         
   Item_Order 
INNER JOIN
   Item ON Item_Order.ItemID = Item.ItemID 
INNER JOIN
   TheOrder ON Item_Order.OrderID = TheOrder.OrderID 
INNER JOIN
   Customer ON TheOrder.CustomerID = Customer.CustomerID
) as Test
GROUP BY 
   CustomerName, ItemName WITH ROLLUP
ORDER BY 
   CustomerName
于 2012-11-20T14:18:45.983 回答