我有一个表,open_price,close_price和profit列。我需要得到4列(余额),其中余额值等于前一个余额行值+货币行利润。请查看下面的说明:
open_date close_date profit
2012-08-14 12:02:46 2012-08-14 14:39:38 14.50
2012-08-14 14:43:08 2012-08-14 15:41:58 -14.50
2012-08-14 15:41:58 2012-08-14 16:09:15 -29.00
2012-08-14 16:09:15 2012-08-14 16:15:04 1.20
2012-08-14 16:26:19 2012-08-14 16:40:37 14.50
2012-08-15 08:25:56 2012-08-15 08:37:37 -1.20
2012-08-15 09:06:26 2012-08-15 12:57:26 -14.50
2012-08-15 12:57:26 2012-08-15 13:08:43 29.00
2012-08-15 13:15:06 2012-08-15 13:20:20 14.50
2012-08-15 13:22:15 2012-08-15 15:23:10 -5.40
我有一个请求并获得新表:
SELECT open_date, close_date, profit, ( 1000 + profit ) AS balance
FROM users_signals
ORDER BY open_date ASC
LIMIT 0 , 30
open_date Ascending close_date profit balance
2012-08-14 12:02:46 2012-08-14 14:39:38 14.50 1014.50
2012-08-14 14:43:08 2012-08-14 15:41:58 -14.50 985.50
2012-08-14 15:41:58 2012-08-14 16:09:15 -29.00 971.00
2012-08-14 16:09:15 2012-08-14 16:15:04 1.20 1001.20
2012-08-14 16:26:19 2012-08-14 16:40:37 14.50 1014.50
2012-08-15 08:25:56 2012-08-15 08:37:37 -1.20 998.80
2012-08-15 09:06:26 2012-08-15 12:57:26 -14.50 985.50
2012-08-15 12:57:26 2012-08-15 13:08:43 29.00 1029.00
2012-08-15 13:15:06 2012-08-15 13:20:20 14.50 1014.50
2012-08-15 13:22:15 2012-08-15 15:23:10 -5.40 994.60
我怎样才能得到这张表:
open_date Ascending close_date profit balance
2012-08-14 12:02:46 2012-08-14 14:39:38 14.50 1014.50
2012-08-14 14:43:08 2012-08-14 15:41:58 -14.50 1000 //1014.50+-14.50
2012-08-14 15:41:58 2012-08-14 16:09:15 -29.00 971.00 //1000+-29.00
2012-08-14 16:09:15 2012-08-14 16:15:04 1.20 972.20 //971.00+1.20
2012-08-14 16:26:19 2012-08-14 16:40:37 14.50 986.70 //972.20+14.50
2012-08-15 08:25:56 2012-08-15 08:37:37 -1.20 985.50 //986.70+-1.20
2012-08-15 09:06:26 2012-08-15 12:57:26 -14.50 971.00 //985.5+-14.50
2012-08-15 12:57:26 2012-08-15 13:08:43 29.00 1000.00 //971.00+29.00
2012-08-15 13:15:06 2012-08-15 13:20:20 14.50 1014.50 //1000.00+14.50
2012-08-15 13:22:15 2012-08-15 15:23:10 -5.40 1009.1 //1014.50-5.40
答案 0 :(得分:3)
以下内容将起作用::
SET @bal=1000;
SELECT open_date, close_date, profit,@bal := @bal+profit AS balance
FROM users_signals
ORDER BY open_date ASC
LIMIT 0 , 30
这会不断更新@bal
答案 1 :(得分:0)
使用这样的子查询:
SELECT open_date, close_date, profit,
(1000 + (SELECT SUM(us.profit)
FROM user_signals us
WHERE us.open_date <= users_signals.open_date)) AS balance
FROM users_signals
ORDER BY open_date ASC
LIMIT 0 , 30