DROP VIEW IF EXISTS STOR.V_GROUPED_REMAINS;
CREATE VIEW STOR.V_GROUPED_REMAINS
AS
SELECT			
	MAX(r.RemainsID::varchar(36))::uuid AS GroupedRemainsID
,	r.Storage
,	r.BillOfGoods
,	SUM(r.Amount) AS Amount
,	r.Price
,	r.PackageType
,	r.QuantityInPackage as Coeff
,	abr.PaymentType
,	r.Series
,	r.ExpirationDate
,	rlpt.PackageType as DefaultPackageType
FROM STOR.T_REMAINS AS r
	join STOR.T_SUPPLIER_CONTRACT_ABR abr on abr.Abr = r.SupplierContractAbr
	left join STOR.T_REMAINS_LINK_PACKAGE_TYPE rlpt on rlpt.Remains = r.RemainsID and rlpt.UnitPrice = '1'
WHERE r.Amount > 0
GROUP BY r.Storage, r.BillOfGoods, r.Price, r.PackageType, abr.PaymentType, r.Series, r.ExpirationDate, rlpt.PackageType, r.QuantityInPackage;