1

我有一个包含 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 查询实现吗?

4

3 回答 3

2
SELECT SUM(Amount) AS ProfitOrLoss FROM TableName GROUP BY Date
于 2012-10-11T22:03:59.667 回答
1

假设Date按照您在预期结果中显示的那样存储,这应该可以工作:

SELECT
   SUM(Amount) AS "Profit/Loss",
   Date
FROM your_table
GROUP BY(Date)

否则 idDate是 type DATEDATETIME或者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是一个很好的提示:

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)中,并且对于分组交易的每一行,您将其增加每日余额

于 2012-10-11T22:03:19.797 回答
1
SELECT SUM(Amount) FROM TableName GROUP BY Date
于 2012-10-11T22:04:27.783 回答