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,但两个项目都被订购了两次。所以我需要实际的总数,而不仅仅是不同的值。
有谁知道我做错了什么?
答案 0 :(得分: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