SQL Server:通过联接两个表来创建视图,并在新列中找到两列的总和

时间:2018-09-29 09:57:45

标签: sql-server tsql view

我有两个表StockInStockOut,由它们的ID号标识。现在,我想创建一个视图以在StockIn.Id = StockOut.Id处找到手头的股票。

这是我一直试图但无法获得结果的SQL代码:

CREATE VIEW [dbo].[StockHand_Total] 
AS 
    SELECT 
        i.Id,
        i.ProductName,
        i.Rate,
        i.Qty,
        So.QtyOut,
        i.Amount,
        x.Balance
    FROM
        dbo.StockIn i 
    JOIN
        StockOut So ON i.Id = So.Id

    SELECT Balance = SUM(Qty - QtyOut)   
GO

1 个答案:

答案 0 :(得分:1)

您可以使用:

CREATE VIEW [dbo].[StockHand_Total] 
AS
    SELECT 
        i.Id,
        i.ProductName,
        i.Rate,
        i.Qty,
        So.QtyOut,
        i.Amount,
        Balance = SUM(COALESCE(i.Qty, 0) - COALESCE(so.QtyOut, 0)) OVER(PARTITION BY i.id)
    FROM
        dbo.StockIn i 
    LEFT JOIN
        StockOut So ON i.Id = So.Id