1

我有一个表、open_price、close_price 和利润列。我需要获得 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 
4

2 回答 2

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

于 2012-08-20T10:15:55.133 回答
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
于 2012-08-20T09:50:31.273 回答