我有两个表StockIn
和StockOut
,由它们的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
答案 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