我有一个包含4列的MySQL表,如下所示。
TransactionID | Item | Amount | Date
------------------------------------
| | |
| | |
我有很多条目,我希望能够做的是创建一个查询,返回每个时间点的总利润/损失列表?
想象一下,我有以下交易:
Bought item for 5
Sold item for 15
Bought item for 5
Sold item for 15
所以我希望它能返回这样的东西。
Profit/Loss | Date
------------------
-5 | 20-10-12
10 | 21-10-12
5 | 22-10-12
20 | 23-10-12
这可以通过MySQL查询吗?
答案 0 :(得分:2)
SELECT SUM(Amount) AS ProfitOrLoss FROM TableName GROUP BY Date
答案 1 :(得分:1)
假设您在预期结果中显示时存储了Date
,这应该有效:
SELECT
SUM(Amount) AS "Profit/Loss",
Date
FROM your_table
GROUP BY(Date)
其他ID Date
的类型为DATE
,DATETIME
或TIMESTAMP
您可以执行以下操作:
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'))
的引用:
编辑(OP评论后)
实现推理SUM here是一个很好的提示:
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;
当然,您将当前总和存储到变量(@csum)中,并且对于分组事务的每一行,您可以将其增加到每日余额
答案 2 :(得分:1)
SELECT SUM(Amount) FROM TableName GROUP BY Date