CREATE VIEW dbo.blItemsListView as
SELECT     tow.ID AS Id, tow.Kod AS Code, tow.Nazwa AS Name, jedn.Kod AS UM,  CONVERT(DECIMAL(16, 4), tow.MasaBruttoValue) AS Weight, 
ISNULL(CONVERT(DECIMAL(16, 4), cena.BruttoValue), 0) AS Price, 
                      ISNULL(stawka.Kod, '') AS TaxDesc, ISNULL(CONVERT(DECIMAL(16, 4), 
                      stawka.StawkaProcent * 100), 0) AS TaxValue,
					  Stany.Stock Stock
FROM         dbo.Towary AS tow LEFT OUTER JOIN                      
                      dbo.Ceny AS cena ON cena.Towar = tow.ID AND cena.Definicja = 8 JOIN
                      dbo.DefStawekVat AS stawka ON tow.DefinicjaStawki = stawka.ID LEFT OUTER JOIN
                      dbo.Jednostki AS jedn ON jedn.ID = tow.Jednostka  
                      LEFT OUTER JOIN 
					  (
						select  z.Towar ItemId, z.Magazyn MagId, 
						SUM(CONVERT(DECIMAL(16, 4),(z.IloscValue * Kierunek))) Stock
						from dbo.Zasoby  z 
						JOIN  dbo.OkresyMag o  ON o.ID = z.Okres and o.Zamkniety = 0
						where Kierunek =1 and  PartiaTyp =1 and z.Magazyn =1 
						GROUP BY  z.Magazyn, z.Towar
						) Stany ON Stany.ItemId = tow.ID
					  

