views:

62

answers:

2

I have a MySQL database with the following table structure:

TransactionType: Transaction_Amount, Transaction_ID, Transaction_Form
Transaction: Transaction_ID, Timestamp
Purchase: Transaction_ID, Item_ID
Items: Item_ID, Client_ID

This is really a two part question (please let me know if i should post these as two separate questions)

1) TransactionType.Transaction_Form is essentially a column to determine if a transaction was cash or credit. Is there a way to combine these two queries?

SELECT SUM(Transaction_Amount) 
FROM Transaction_Type WHERE Transaction_Form = 'cash'

and

SELECT SUM(Transaction_Amount) 
FROM Transaction_Type WHERE Transaction_Form = 'credit'

2)I have the need to select these two transaction_amount's based upon the client_id being used.

The only way I can think of to do this is something like:

SELECT Transaction_Amount FROM Transaction_Type 
JOIN Transaction ON Transaction_Type.Transaction_ID=Transaction.Transaction_ID
JOIN Purchase ON Transaction.Transaction_ID = Purchase.Transaction_ID
JOIN Items ON Purchase.Item_ID = Item.Item_ID
WHERE Items.Client_ID = $clientId

Which is obviously not all that pretty...

Do I need to add a client_id column into transaction? Would that be redundant?

-thanks

+2  A: 

1:

SELECT transaction_form, SUM(transaction_amount) 
FROM transaction_type 
GROUP BY transaction_form
rosscj2533
That will list the sums for *all* `transaction_form`, not just cash and credit.
OMG Ponies
That's true, I assumed that would be wanted, but since he explicitly said 'combine these two queries', your answer is more accurate.
rosscj2533
sorry, 'combine these two queries' is a bit ambiguous... not sure how to word that one properly
Derek Adair
+2  A: 

Part 1:

Use:

SELECT SUM(tt.transaction_amount)
  FROM TRANSACTION_TYPE tt
 WHERE tt.transaction_form IN ('cash', 'credit')

...if you want the transaction_amount for both combined. If you want them separate, use:

  SELECT tt.transaction_form,
         SUM(tt.transaction_amount)
    FROM TRANSACTION_TYPE tt
   WHERE tt.transaction_form IN ('cash', 'credit')
GROUP BY tt.transaction_form

Part 2:

Use:

SELECT tt.transaction_amount
  FROM TRANSACTION_TYPE tt
  JOIN PURCHASE p ON p.transaction_id = tt.transaction_id
  JOIN ITEMS i ON i.item_id = p.item_id
 WHERE i.client_id = ?
OMG Ponies