CREATE view vv_RegistryBankTransfer
as
select t1.Oid Oid, 
       t1.RegistryHeader RegistryHeader, 
       t1.AmountHUF AmountHUF, 
       t1.AmountDEV AmountDEV, 
       t1.DatePayment DatePayment, 
       t1.IsBlocked IsBlocked, 
       t1.Note Note, 
       t1.BankSavedFileName BankSavedFileName,
       ifnull(t3.BallanceHUF,t2.F_AmountBruttoHUF) BallanceHUF,
       ifnull(t3.BallanceDEV,t2.F_AmountBruttoDEV) BallanceDEV,
       t1.AmountHUF-ifnull(t3.BallanceHUF,t2.F_AmountBruttoHUF) DifferenceHUF,
       t1.AmountDEV-ifnull(t3.BallanceDEV,t2.F_AmountBruttoDEV) DifferenceDEV,
       case when round(ifnull(t3.BallanceHUF,t2.F_AmountBruttoHUF),2)=0 then 0
            when ifnull(t3.BallanceHUF,t2.F_AmountBruttoHUF)>=t1.AmountHUF then t1.AmountHUF
            when ifnull(t3.BallanceHUF,t2.F_AmountBruttoHUF)<=t1.AmountHUF then ifnull(t3.BallanceHUF,t2.F_AmountBruttoHUF)
       end OfferedHUF,
       case when round(ifnull(t3.BallanceDEV,t2.F_AmountBruttoDEV),2)=0 then 0
            when ifnull(t3.BallanceDEV,t2.F_AmountBruttoDEV)>=t1.AmountDEV then t1.AmountDEV
            when ifnull(t3.BallanceDEV,t2.F_AmountBruttoDEV)<=t1.AmountDEV then ifnull(t3.BallanceDEV,t2.F_AmountBruttoDEV)
       end OfferedDEV,
       t1.BankPrepareName BankPrepareName                      
  from RegistryBankTransfer t1 
       join RegistryHeader t2 on t1.RegistryHeader=t2.Oid 
       left join PCIGroup t3 on t2.CustomersFrom=t3.CustomersFrom 
            and t2.Customers=t3.Customers and t3.PartnerType=1 and t2.DocumentNumber=t3.ConnectInfo
  where t1.GCRecord is null and t2.RegistryAcceptState=0