Ledger Report Logic in Stored Procedure

后端 未结 3 766
悲&欢浪女
悲&欢浪女 2021-01-22 23:25

i have a Stored Procedure called \"Patient Ledger Report\" where i need to show the day to day transaction details and balance amount of the patients.i was providing you one sa

3条回答
  •  一生所求
    2021-01-22 23:49

    Try this and tell me if it work with other sample data too.

    create table #Patient_ledger (PATIENT_NAME varchar(250),PATIENT_NBR bigint
    ,BILLNO varchar(250),BILLAMOUNT bigint,PAID_AMOUNT bigint)
    
    Insert into #Patient_ledger (Patient_name ,Patient_nbr ,billno 
    ,billamount ,paid_amount )
    
    select 'ABC',1,'DUE_BILL_ABC_1',100,50
    union all
    select 'ABC',1,'DUE_BILL_ABC_2',160,90
    UNION ALL
    select 'ABC',1,'DEPOSIT_BILL_ABC',0,40
    UNION ALL
    select 'XYZ',2,'DEPOSIT_BILL_XYZ',0,70
    UNION ALL
    select 'XYZ',2,'DUE_BILL_XYZ_1',100,30
    
    
    SELECT PATIENT_NBR PATIENT_NUMBER
        ,BILLNO
        ,BILLAMOUNT
        ,PAID_AMOUNT
        ,CASE 
            WHEN billamount = 0
                AND lag((BILLAMOUNT - PAID_AMOUNT), 1, 0) OVER (
                    PARTITION BY PATIENT_NBR ORDER BY PATIENT_NBR
                    ) = 0
                THEN 0
            ELSE SUM((BILLAMOUNT - PAID_AMOUNT)) OVER (
                    PARTITION BY PATIENT_NBR ORDER BY PATIENT_NBR ROWS UNBOUNDED PRECEDING
                    )
            END Balance
    FROM #Patient_ledger
    
    Drop table #Patient_ledger
    

提交回复
热议问题