Expand|Select|Wrap|Line Numbers
- mysql> describe acount;
- +----------+---------------+------+-----+---------+----------------+
- | Field | Type | Null | Key | Default | Extra |
- +----------+---------------+------+-----+---------+----------------+
- | uniqueID | bigint(20) | NO | PRI | NULL | auto_increment |
- | amount | decimal(20,0) | NO | | NULL | |
- | BALANCE | decimal(20,2) | NO | | 0.00 | |
- +----------+---------------+------+-----+---------+----------------+
- 3 rows in set (0.04 sec)
Expand|Select|Wrap|Line Numbers
- mysql> select * from acount;
- +----------+--------+---------+
- | uniqueID | amount | BALANCE |
- +----------+--------+---------+
- | 8 | 200 | 0.00 |
- | 9 | 100 | 0.00 |
- | 10 | 200 | 0.00 |
- | 11 | 5 | 0.00 |
- | 12 | 13 | 0.00 |
- | 13 | 145 | 0.00 |
- | 14 | -100 | 0.00 |
- | 15 | 125 | 0.00 |
- | 16 | 15 | 0.00 |
- +----------+--------+---------+
- 9 rows in set (0.00 sec)
When i enter this command:
Expand|Select|Wrap|Line Numbers
- mysql> SELECT uniqueID, amount, amount + coalesce( (
- ->
- -> SELECT sum( amount )
- -> FROM acount b
- -> WHERE b.uniqueID < a.uniqueID ) , 0
- -> ) AS BALANCE
- -> FROM acount a;
Expand|Select|Wrap|Line Numbers
- +----------+--------+---------+
- | uniqueID | amount | BALANCE |
- +----------+--------+---------+
- | 8 | 200 | 200 |
- | 9 | 100 | 300 |
- | 10 | 200 | 500 |
- | 11 | 5 | 505 |
- | 12 | 13 | 518 |
- | 13 | 145 | 663 |
- | 14 | -100 | 563 |
- | 15 | 125 | 688 |
- | 16 | 15 | 703 |
- +----------+--------+---------+
- 9 rows in set (0.00 sec)
when i check the balance field again, the result return to default value.
Expand|Select|Wrap|Line Numbers
- mysql> select balance from acount;
- +---------+
- | balance |
- +---------+
- | 0.00 |
- | 0.00 |
- | 0.00 |
- | 0.00 |
- | 0.00 |
- | 0.00 |
- | 0.00 |
- | 0.00 |
- | 0.00 |
- +---------+
- 9 rows in set (0.00 sec
Just as table below:
Expand|Select|Wrap|Line Numbers
- +----------+--------+---------+
- | uniqueID | amount | BALANCE |
- +----------+--------+---------+
- | 8 | 200 | 200 |
- | 9 | 100 | 300 |
- | 10 | 200 | 500 |
- | 11 | 5 | 505 |
- | 12 | 13 | 518 |
- | 13 | 145 | 663 |
- | 14 | -100 | 563 |
- | 15 | 125 | 688 |
- | 16 | 15 | 703 |
- +----------+--------+---------+