2012-11-20 69 views
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 

結果:ROLLUP只總結了不同的值在SQL Server 2008中

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 

正如你可以看到使用匯總給出的總計增加了30.54和21.88這涉及到52.42,但兩個項目是有序的兩倍。所以我需要實際的總數,而不僅僅是爲了不同的值。

有誰知道我做錯了什麼?

+1

歡迎使用StackOverflow:如果您發佈代碼,XML或數據樣本,請**在文本編輯器中突出顯示這些行,然後單擊編輯器工具欄上的「代碼示例」按鈕(「{}」),以良好地格式化和語法突出顯示它! –

回答

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 
+0

或者也許只是從組中刪除Item_Order.PriceAtDate將做伎倆?! – nils

+0

謝謝尼爾斯,它仍然沒有真正做到這一點。它使查詢似乎工作,但我知道在我的數據庫中,一個客戶可以訂購/訂購了超過1個相同的物品,但彙總功能只會添加不同的值。例如,顧客詹姆斯訂購兩把錘子和三把烙鐵,但它只加起來一把錘子和一把烙鐵 – user1809104

+0

嗯......你解決了嗎? – nils