I want to create a database schema for a system that holds customers and the charges and payments they do. What is the recommended approach so that I can later get a list of all customers with their total charges and payments using only one query?
A single query should return a result like this:
NAME | TotalCharges | TotalPayments
John 80 100
Nick 100 90
I am thinking to create two separate tables, one for the charges and one for the payments.
CUSTOMERS
-ID
-NAME
CHARGES
-ID
-CUSTOMER_ID
-AMOUNT
PAYMENTS
-ID
-CUSTOMER_ID
-AMOUNT
Another approach is to create one table for both charges and payments, using one column for each, like this:
CUSTOMERS
-ID
-NAME
CHARGES_AND_PAYMENTS
-ID
-CUSTOMER_ID
-CHARGE_AMOUNT
-PAYMENT_AMOUNT
Another approach is to use one table for both charges and payments, using a TRANSACTION_TYPE flag. 0->Payment, 1->Charge, but if I use this approach I would not be able to get total charges and payments for a customer using one query (or can I?)
CUSTOMERS
-ID
-NAME
CHARGES_AND_PAYMENTS
-ID
-CUSTOMER_ID
-TRANSACTION_TYPE (Flag: 0=Payment, 1=Charge)
-AMOUNT
Which is the best approach?
Do a sum on the Charges and Payments table per Customer ID