I had this question asked of me on a job interview, and I can't seem to find the right way to do this. I'm just looking for the answer so if it comes up again another time I'll have more of an idea of what should be done.

Table A has 3 columns. ID, CustomerName, and Amount

Values (1, "Someone", 20000)

Table B has 3 Columns. CustID, Date, Payment. Values

(1, 1/1/2014, 100)
(1, 2/1/2014, 200)
(1, 3/1/2014, 500)
(1, 4/1/2014, 175)

What they want to know is after each payment has been made, what is the remaining balance on the account. So the output would be:

Customer Name, Payment Amount, Remaining Balance

For each payment.

How would someone go about accomplishing this since I've stumped all of my database friends and can't seem to find the info on google....

有帮助吗?

解决方案

In databases that support the ANSI standard cumulative sum syntax, you would simply do:

select a.CustomerName, b.Payment,
       (a.amount - sum(b.payment) over (partition by a.id order by date)) as RemainingBalance
from tablea a left outer join
     tableb b
     on a.id = b.id;

In other databases, I would use a correlated subquery.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top