2016-04-05 150 views
0

我正嘗試在用戶中爲SQL創建一個視圖。 (如下所示)在這裏,我想Sum dbo.WipPartBook.QtySupplied的值,當列dbo.WipPartBook.Job的值是相同的。基於同一視圖中的另一列在SQL視圖中插入總和

SELECT  TOP (100) PERCENT dbo.vwSTKCF.StockCode, dbo.vwSTKCF.Cavity, dbo.vwSTKCF.Mass, dbo.vwSTKCF.Material, dbo.WipPartBook.Job, 
        dbo.WipPartBook.QtySupplied, dbo.WipPartBook.TrnDate 
FROM   dbo.WipPartBook INNER JOIN 
        dbo.InvMaster INNER JOIN 
        dbo.WipMaster ON dbo.InvMaster.StockCode = dbo.WipMaster.StockCode ON dbo.WipPartBook.Job = dbo.WipMaster.Job LEFT OUTER JOIN 
        dbo.vwSTKCF ON dbo.InvMaster.StockCode = dbo.vwSTKCF.StockCode 
WHERE  (dbo.vwSTKCF.StockCode = 'SC2020-01-00') 
ORDER BY dbo.vwSTKCF.StockCode 
+0

您能給一些示例數據,使其更容易給你一個優化的查詢?謝謝 – swe

回答

0

您使用的是哪種SQL Server版本?如果它是當前一個你應該考慮的窗口功能,允許,除其他外,通過「分組」列(dbo.WipPartBook.Job)分區總數 看看這裏的介紹:Microsoft BOL

編輯:增加了一個(未經測試)例如:

SELECT  TOP (100) PERCENT dbo.vwSTKCF.StockCode, dbo.vwSTKCF.Cavity, dbo.vwSTKCF.Mass, dbo.vwSTKCF.Material, dbo.WipPartBook.Job, 
       dbo.WipPartBook.QtySupplied, dbo.WipPartBook.TrnDate, 

SUM(dbo.WipPartBook.QtySupplied) OVER (PARTITION BY dbo.WipPartBook.Job) AS Total 

FROM   dbo.WipPartBook INNER JOIN 
       dbo.InvMaster INNER JOIN 
       dbo.WipMaster ON dbo.InvMaster.StockCode = dbo.WipMaster.StockCode ON dbo.WipPartBook.Job = dbo.WipMaster.Job LEFT OUTER JOIN 
       dbo.vwSTKCF ON dbo.InvMaster.StockCode = dbo.vwSTKCF.StockCode 
WHERE  (dbo.vwSTKCF.StockCode = 'SC2020-01-00') 
ORDER BY dbo.vwSTKCF.StockCode 
+1

雖然這個鏈接可能回答這個問題,但最好在這裏包含答案的基本部分,並提供參考鏈接。如果鏈接頁面更改,則僅鏈接答案可能會失效 – Nehal

0
SELECT dbo.WipPartBook.Job, sum(dbo.WipPartBook.QtySupplied)  
    FROM dbo.WipMaster  
    JOIN dbo.WipPartBook 
      ON dbo.WipPartBook.Job = dbo.WipMaster.Job 
WHERE dbo.WipMaster.StockCode = 'SC2020-01-00' 
GROUP BY dbo.WipPartBook.Job 
Order BY dbo.WipPartBook.Job 
相關問題