2016-03-15 125 views
0

enter image description here enter image description here 這裏的查詢如何在MSSQL查詢中添加總計的彙總行?

SELECT 
MAX (Supplier.SupplierName) as Supplier, 
MAX (Department.Name) as Department, 
MAX (Category.Name) as Category, 
MAX (ItemClass.ItemLookupCode) as Matrix, 
MAX (Item.ItemLookupCode) as ItemLookupCode, 
MAX (Item.Description) as Description, 
SUM (TransactionEntry.Quantity) as QtySold, 
MAX (Item.Cost) as Cost, 
MAX (Item.Price) as Price, 
MAX (TransactionEntry.Price) as SoldPrice, 
SUM (TransactionEntry.Price * TransactionEntry.Quantity) as TotalSale, 
MAX (Item.Quantity) as OnHand 

    FROM  TransactionEntry 
    INNER JOIN [Transaction] WITH(NOLOCK) 
       ON TransactionEntry.TransactionNumber = [Transaction].TransactionNumber AND TransactionENtry.ItemType <> 9 AND TransactionEntry.StoreID = [Transaction].StoreID 
    INNER JOIN Batch WITH(NOLOCK) 
       ON [Transaction].BatchNumber = Batch.BatchNumber AND [Transaction].StoreID = Batch.StoreID 
    LEFT JOIN Item WITH(NOLOCK) 
       ON TransactionEntry.ItemID = Item.ID 
    LEFT JOIN Department WITH(NOLOCK) 
       ON Item.DepartmentID = Department.ID 
    LEFT JOIN Category WITH(NOLOCK) 
       ON Item.CategoryID = Category.ID 
    LEFT JOIN Supplier WITH(NOLOCK) 
       ON Item.SupplierID = Supplier.ID 
    LEFT JOIN ReasonCode AS ReasonCodeDiscount WITH(NOLOCK) 
       ON TransactionEntry.DiscountReasonCodeID = ReasonCodeDiscount.ID 
    LEFT JOIN ReasonCode AS ReasonCodeTaxChange WITH(NOLOCK) 
       ON TransactionEntry.TaxChangeReasonCodeID = ReasonCodeTaxChange.ID 
    LEFT JOIN ReasonCode AS ReasonCodeReturn WITH(NOLOCK) 
       ON TransactionEntry.ReturnReasonCodeID = ReasonCodeReturn.ID 
    LEFT JOIN Store ON [Transaction].StoreID = Store.ID 
    LEFT JOIN ItemClassComponent WITH(NOLOCK) 
     ON Item.ID = ItemClassComponent.ItemID 
    LEFT JOIN ItemClass WITH(NOLOCK) 
     ON ItemClassComponent.ItemClassID = ItemClass.ID 

WHERE DATEDIFF(week, [Transaction].Time, GETDATE()) = 1 AND 
Supplier.SupplierName = 'Name' 

GROUP BY Item.ItemLookupCode 

這裏的查詢和如何添加摘要行總數爲一些列的?我嘗試了幾件事,但找不到任何東西...

請幫忙!!!!

http://i29.photobucket.com/albums/c259/xkrntamax/Capture_zps511d8kun.jpg

+0

請您提供一些示例表中的數據? – Wanderer

+0

在使用NOLOCK提示繼續亂拋垃圾數據庫之前,您應該先閱讀這些內容......除非您確定的結果大部分時間都基本準確。由於這看起來像一個財務應用程序,我懷疑缺失和/或重複的行是可以接受的。 http://blogs.sqlsentry.com/aaronbertrand/bad-habits-nolock-everywhere/ –

+0

我是否需要添加行查詢來計算總數? –

回答

2

您可能正在尋找grouping setswith rollup

更改group by子句:

GROUP BY GROUPING SETS ((Item.ItemLookupCode),()) 
+0

我得到相同的結果。我是否需要添加查詢來計算總行數? –

+0

當您運行此查詢時,它應該添加一個額外的行,這是適用於所有數據的分組條件。這就是'()'用'GROUPING SETS'做的事情。結果不應該是一樣的。 –

+0

謝謝!它的工作原理,但有什麼方法可以顯示只需要求和的列? –