Ledger Report Logic in Stored Procedure

后端 未结 3 765
悲&欢浪女
悲&欢浪女 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-23 00:04

    If you are able to put there also order discriminator, it could seems like this: (I consider also fact that there can be more DUE/DEPOSITS for one PATIENT_NBR)

    IF OBJECT_ID('tempdb..#Patient_ledger') IS NOT NULL DROP TABLE #Patient_ledger
        CREATE TABLE #Patient_ledger 
        (ID INT IDENTITY, 
         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
    
    
    ;WITH CTE AS (
    SELECT PATIENT_NBR, 
           BILLNO,
           PAID_AMOUNT,
           BILLAMOUNT,
           BILLAMOUNT-PAID_AMOUNT AS BALANCE, 
           ROW_NUMBER() OVER (PARTITION BY PATIENT_NBR ORDER BY ID) AS RN
    FROM #Patient_ledger)
    
    SELECT a.PATIENT_NBR,
           a.BILLNO,
           a.BILLAMOUNT,
           a.PAID_AMOUNT,
           CASE WHEN ISNULL(LAG(a.BALANCE + ISNULL(x.ADDS,0)) OVER (PARTITION BY a.PATIENT_NBR ORDER BY a.RN),0) + a.BILLAMOUNT - a.PAID_AMOUNT < 0 
                THEN 0
                ELSE a.BALANCE + ISNULL(x.ADDS,0)
           END AS FINAL_BALANCE
    
    FROM CTE a
    CROSS APPLY (SELECT SUM(BALANCE) AS ADDS 
                    FROM CTE f 
                        WHERE f.PATIENT_NBR = a.PATIENT_NBR AND f.RN < a.RN) x
    

提交回复
热议问题