Ich habe es wie folgt versucht, es kann Ihnen helfen
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