Saya sudah mencoba seperti di bawah ini mungkin membantu Anda
SELECT Patient_nbr,
billno,
billamount,
PAID_AMOUNT,
CASE
WHEN RNO > 1 THEN Sum(billamount - PAID_AMOUNT)
OVER(
PARTITION BY Patient_nbr
ORDER BY RNO)
ELSE Iif(( billamount - PAID_AMOUNT ) < 0, 0, billamount - PAID_AMOUNT)
END
FROM (SELECT *,
Row_number()
OVER(
PARTITION BY Patient_nbr
ORDER BY Patient_nbr) AS RNO
FROM #Patient_ledger) A