Reputation: 1518
I have a MySQL table with 4 columns as follows.
TransactionID | Item | Amount | Date
------------------------------------
| | |
| | |
I have a lot of entries and what I want to be able to do is create a query that returns a list of the total Profit/Loss at each point in time?
Imagine I had the following transactions:
Bought item for 5
Sold item for 15
Bought item for 5
Sold item for 15
So I would want it to return something like this.
Profit/Loss | Date
------------------
-5 | 20-10-12
10 | 21-10-12
5 | 22-10-12
20 | 23-10-12
Is this possible with a MySQL query?
Upvotes: 1
Views: 5328
Reputation: 9006
Assuming that Date
is stored as you show on the expected result this should work:
SELECT
SUM(Amount) AS "Profit/Loss",
Date
FROM your_table
GROUP BY(Date)
Otherwise id Date
is of type DATE
, DATETIME
or TIMESTAMP
you could do something like this:
SELECT
SUM(Amount) AS "Profit/Loss",
DATE_FORMAT(Date, '%d-%m-%y') AS Date
FROM your_table
GROUP BY(DATE_FORMAT(Date, '%d-%m-%y'))
references:
EDIT (after OP's comment)
to achieve the comulative SUM here is a good hint:
SET @csum := 0;
SELECT
(@csum := @csum + x.ProfitLoss) as ProfitLoss,
x.Date
FROM
(
SELECT
SUM(Amount) AS ProfitLoss,
DATE_FORMAT(Date, '%d-%m-%y') AS Date
FROM your_table
GROUP BY(DATE_FORMAT(Date, '%d-%m-%y'))
) x
order by x.Date;
essentialy you store the current sum into a variable (@csum) and for each row of the grouped transactions you increase it by the daily balance
Upvotes: 1
Reputation: 1131
SELECT SUM(Amount) AS ProfitOrLoss FROM TableName GROUP BY Date
Upvotes: 2