

CREATE VIEW [dbo].[ApiWmsStocksCalculationView]
as
select s.RepositoryId, ISNULL(sl.Adress,'') LocationAdress, s.LocationId, s.ItemId, s.Quantity  [Quanity],s.ItemFeatures,s.StockBarcode Barcode,  ISNULL(i.UM,'') UM,
s.TS, ISNULL(i.Code,'') ItemCode, ISNULL(i.Name,'') ItemName
from 
(select ItemId,ItemFeatures, StockBarcode,LocationId, l.RepositoryId, SUM( l.Direction*Quantity) Quantity , MAX(l.TS) TS  from dbo.ApiWmsDocLines l
JOIN dbo.ApiWmsDocuments d ON d.Id = l.DocumentId and d.StateId>=2
group by ItemId, ItemFeatures, StockBarcode, LocationId, l.RepositoryId) s
LEFT OUTER JOIN  dbo.ApiItemsView i ON s.Itemid = i.ItemId
LEFT OUTER JOIN  dbo.ApiStockLocations sl ON s.LocationId = sl.Id
GO


