Create table test (
transdate datetime default null,
description varchar(16) default null,
transstatus integer default 0,
amount decimal(19,4) default null);insert into test value ('2010-12-06 09:36:45', 'INWARD CR-IBG', 1, 2000.00),
('2010-12-06 09:43:28', 'Paid', 2, 1000.00),
('2010-12-06 09:50:04', 'INWARD CR-IBG', 1, 3000.00);算出他们的BALANCE,1是进,2是出。
结果是:
'2010-12-06 09:36:45', 'INWARD CR-IBG', 1, 2000.00, 2000.00
'2010-12-06 09:43:28', 'Paid', 2, 1000.0000, 1000.00
'2010-12-06 09:50:04', 'INWARD CR-IBG', 1, 3000.0000, 4000.00
头晕,

解决方案 »

  1.   

    mysql> select * from test;
    +---------------------+---------------+-------------+-----------+
    | transdate           | description   | transstatus | amount    |
    +---------------------+---------------+-------------+-----------+
    | 2010-12-06 09:36:45 | INWARD CR-IBG |           1 | 2000.0000 |
    | 2010-12-06 09:43:28 | Paid          |           2 | 1000.0000 |
    | 2010-12-06 09:50:04 | INWARD CR-IBG |           1 | 3000.0000 |
    +---------------------+---------------+-------------+-----------+
    3 rows in set (0.03 sec)mysql> select *,
        -> (select sum(amount*if(transstatus=1,1,-1)) From test where transdate<=a.transdate) AS balance
        -> from test a;
    +---------------------+---------------+-------------+-----------+-----------+
    | transdate           | description   | transstatus | amount    | balance   |
    +---------------------+---------------+-------------+-----------+-----------+
    | 2010-12-06 09:36:45 | INWARD CR-IBG |           1 | 2000.0000 | 2000.0000 |
    | 2010-12-06 09:43:28 | Paid          |           2 | 1000.0000 | 1000.0000 |
    | 2010-12-06 09:50:04 | INWARD CR-IBG |           1 | 3000.0000 | 4000.0000 |
    +---------------------+---------------+-------------+-----------+-----------+
    3 rows in set (0.01 sec)mysql>
      

  2.   

    mysql> select a.*,sum(b.amount*Case b.transstatus when 1 then 1 when 2 then -1 End) as balance
        -> from test a,test b
        -> where a.transdate>=b.transdate
        -> Group by a.transdate;
    +---------------------+---------------+-------------+-----------+-----------+
    | transdate           | description   | transstatus | amount    | balance   |
    +---------------------+---------------+-------------+-----------+-----------+
    | 2010-12-06 09:36:45 | INWARD CR-IBG |           1 | 2000.0000 | 2000.0000 |
    | 2010-12-06 09:43:28 | Paid          |           2 | 1000.0000 | 1000.0000 |
    | 2010-12-06 09:50:04 | INWARD CR-IBG |           1 | 3000.0000 | 4000.0000 |
    +---------------------+---------------+-------------+-----------+-----------+
    3 rows in set (0.00 sec)mysql>写法很多,除此之外还有 from test a inner join test b on a.transdate>=b.transdate 或者 left join
    IF 和 case when, 甚至还可以 interval, 2*(1.5-transdate) 等等。
      

  3.   

    看CSDN帮助上,删除后会把可用分还给你。如果你确定需要删除的话,可以帮你仅保留这个贴子,其它删除。 但我个人不知道分数是否会返还。可以拿你做个试验。
      

  4.   

    我刚才也是用CASE WHEN来写,写着写着,头很晕,所以就开帖了。想不到一下子开了这么多帖。