I have the following table:
Transactions
============
id
date
transaction_type
product_id
stock_id
value
Typical Data for table Transactions
===================================
id | date | transaction_type | product_id | stock_id | value
1 | 2008-07-20 20:00:00 | S | 1 | 1 | 15.00
2 | 2008-07-31 20:00:00 | D | 1 | 1 | 15.00
3 | 2008-08-01 12:30:00 | R | 1 | 1 | 15.00
4 | 2008-08-01 19:00:00 | S | 1 | 1 | 15.00
5 | 2008-08-01 20:00:00 | S | 1 | 2 | 15.00
6 | 2008-08-01 21:00:00 | D | 2 | 1 | 20.00
The transaction_types are as follows:
S is an item being sold
D is an item being dispatched or sold and dispatched in the sale transaction
R is an item being returned (refunded)
Now, what I want to do is create a report that will sum the sales + despatched - returned value for each product, but only summing the latest value
For example, from the above data I would want the following result:
product_id | income
1 | 30
2 | 20
I had thought of doing the following:
Code:
"SELECT product_id, (SUM(IF(S.transaction_type = 'S', S.value, 0)) + SUM(IF(S.transaction_type = 'D', S.value, 0)) - SUM(IF(S.transaction_type = 'R', S.value, 0))) AS income FROM transactions GROUP BY product_id"
This works fine, except where a product has first been sold than dispatched in two separate transactions where it will double count...
Does anyone have any ideas as to how I would only sum the most recent value for each stock without having to resort to multiple queries?
I have no control over the database structure
Any help is gratefully appreciated
I should add I'm using mysql 5