
IF  EXISTS (SELECT * FROM SYS.VIEWS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[V_PG_CRED_VLR_PGTO]'))
    DROP VIEW [DBO].[V_PG_CRED_VLR_PGTO]    
GO

CREATE VIEW [dbo].[V_PG_CRED_VLR_PGTO]
AS
SELECT     
        dbo.PG_DEB.CD_EMP, 
        dbo.PG_DEB.CD_FILIAL, 
        dbo.PG_DEB.CD_PG_CRED,
        dbo.PG_DEB.CD_DP_LANC,
        dbo.PG_DEB.DT_PAG,
        dbo.PG_CRED.VLR_DP + dbo.PG_CRED.VLR_DESP_OUTR - ISNULL((SELECT 
                        ISNULL(SUM(DpAnt.VL_PGTO),0) 
         FROM
                dbo.PG_DEB DpAnt
         WHERE
                dbo.PG_DEB.CD_EMP = DpAnt.CD_EMP AND
                dbo.PG_DEB.CD_FILIAL = DpAnt.CD_FILIAL AND
                dbo.PG_DEB.CD_PG_CRED = DpAnt.CD_PG_CRED
                ),0) AS VLR_SLD,                
        ISNULL(SUM(dbo.PG_DEB.VL_PGTO),0) AS VLR_PGTO, 
		ISNULL(SUM(dbo.PG_DEB.VL_DESC),0) AS VLR_DESC, 
        ISNULL(SUM(dbo.PG_DEB.VL_JUR), 0) AS VLR_JUROS, 
        ISNULL(SUM(dbo.PG_DEB.VL_IMP), 0) AS VLR_IMPOSTO,
        ISNULL(SUM(dbo.PG_DEB.VLR_DEVOLUCAO), 0) AS VLR_DEVOLUCAO,
        dbo.PG_CRED.VLR_DESP_OUTR
FROM         
        dbo.PG_DEB 
        INNER JOIN dbo.PG_CRED ON 
        dbo.PG_DEB.CD_EMP = dbo.PG_CRED.CD_EMP AND 
        dbo.PG_DEB.CD_FILIAL = dbo.PG_CRED.CD_FILIAL AND 
		dbo.PG_DEB.CD_PG_CRED = dbo.PG_CRED.CD_PG_CRED
GROUP BY 
        dbo.PG_DEB.CD_EMP, 
        dbo.PG_DEB.CD_FILIAL, 
        dbo.PG_DEB.CD_PG_CRED, 
        dbo.PG_DEB.DT_PAG,
        dbo.PG_DEB.CD_DP_LANC,
        dbo.PG_CRED.VLR_DESP_OUTR,
        dbo.PG_CRED.VLR_DP
