IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[STOR].[V_SI_MDLP_PAYMENT_TYPE]'))
DROP VIEW [STOR].[V_SI_MDLP_PAYMENT_TYPE]
GO
IF  EXISTS (SELECT * FROM sys.tables WHERE object_id = OBJECT_ID(N'[STOR].[V_SI_MDLP_PAYMENT_TYPE]'))
DROP TABLE [STOR].[V_SI_MDLP_PAYMENT_TYPE]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE VIEW [STOR].[V_SI_MDLP_PAYMENT_TYPE]
AS

select 
	si.InvoiceID
,	case when si.PaymentType is not null then pt.MarkType
				when tt.c > 1 then 5 else tt.MarkType end as MdlpPaymentType
from STOR.T_STORAGE_INVOICE si
left join STOR.T_PAYMENT_TYPE pt on pt.Code = si.PaymentType
outer apply
(
	select 
		max(ptIi.MarkType) as MarkType
	,	count(distinct ptIi.MarkType) as c
	from STOR.T_INVOICE_ITEM ii
	join STOR.T_SUPPLIER_CONTRACT_ABR abr on abr.Abr = ii.SupplierContractAbr
	left join STOR.T_PAYMENT_TYPE ptIi on ptIi.Code = abr.PaymentType
	where ii.StorageInvoice = si.InvoiceID
	group by ii.StorageInvoice
) tt
