问题
Consider the following Tables:
Now before I continue I should preface this by stating that I'm not an accountant (which if you happen to be an accountant reading this probably shows!!)
I have an invoices table and a related InvoicePayments table and a separate Contacts statements table. My Intention is to provide the end user with the ability to create numbered statements for clients that in theory , at least, could be called back at any time in the future. Logically It should be possible to create a straightforward query that given an input parameter of the opening balance should be able to take the sum of those invoices belonging to a certain contact with an outstanding balance > 0 (from a given period) add it to that outstanding balance and do likewise with the invoice payments from the same period only this time subtracting it from the outstanding balance, leaving one with a final closing balance for that period.
What I would like to know from those of you with more experience in creating complex queries that I have is if, given the table structures you see above, it would be possible to create a stored procedure taking openingbalance, start and end dates as input parameters and have it produce a table of invoice / invoice payment transactions in date order (defaulting to invoice first on dates where there are both) that I could then use as the base for a physical paper report that I would also like to produce.
I don't expect anyone to write the query for me, I really want to know if it's feasible from the given structure and perhaps have you provide a subtle pointer in the right direction for me to start producing the query. If I get stuck I can always come back but for now I'd really like to know if it's possible, and perhaps more importantly if not why not. What Did I miss in the table structures?
回答1:
The answer is yes, if you have one more table, like customer to connect ContactsStatements
to the other tables. If ContactsStatements.ContactId
is customer contact and you have table with list of customers, then you can join ContactsStatements.ContactId = [customer].ContactId
and then [customer].CustomerId = Invoices.CustomerId
If you are able to achieve this, you can create mentioned procedure without any problem.
来源:https://stackoverflow.com/questions/35718132/creating-financial-statements-in-sql