我有一个 MySQL 表,我在表中显示借方、贷方和余额。我已将以下定义、示例数据和代码加载到 SQL Fiddle 中:
CREATE TABLE chequebook (
entry_date timestamp default now() PRIMARY KEY,
entry_item varchar(48) NOT NULL DEFAULT '',
entry_amount decimal(10,2) NOT NULL DEFAULT 0.00
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO chequebook (entry_date,entry_item,entry_amount) VALUES
('2010-01-02 12:34:00','Deposit A',215.56),
('2010-01-02 21:44:00','Withdrawal A' ,-23.34),
('2010-01-03 10:44:00','Withdrawal B',-150.15),
('2010-01-03 15:44:00','Deposit B',154.67),
('2010-01-04 18:44:00','Withdrawal C',-65.09),
('2010-01-05 08:44:00','Withdrawal D',-74.23),
('2010-01-06 14:44:00','Deposit C',325.12),
('2010-01-06 20:44:00','Withdrawal E',-80.12),
('2010-01-07 04:44:00','Withdrawal F',-110.34),
('2010-01-07 16:44:00','Withdrawal G',-150.25),
('2010-01-08 16:44:00','Withdrawal H',-23.90),
('2010-01-08 21:44:00','Withdrawal I',-75.66),
('2010-01-08 22:44:00','Deposit C',275.78),
('2010-01-09 11:44:00','Withdrawal K',-85.99),
('2010-01-09 21:44:00','Withdrawal J',-100.00);
set @depos=0;
set @total=0;
select
entry_date,
entry_item,
entry_amount,
if( entry_amount>0, @depos:=entry_amount, @depos:=@depos+entry_amount ) as depos_bal,
@total:=@total+entry_amount as net_bal
from chequebook
order by entry_date;
当我想从 PHP MYSQL 查询向 net_bal
列添加期初余额时,我遇到了问题。
我在将期初余额添加到第一列时遇到问题,之后它应该从所需字段中减去或加上。
例如:
| entry_date | entry_item | entry_amount | depos_bal | net_bal |
|---------------------------|--------------|--------------|-----------|---------|
| January, 02 2010 12:34:00 | Deposit A | 215.56 | 5215.56 | 5215.56 | <--- 5000 is openingbalance
| January, 02 2010 21:44:00 | Withdrawal A | -23.34 | 5192.22 | 5192.22 |
| January, 03 2010 10:44:00 | Withdrawal B | -150.15 | 5042.07 | 5042.07 |
期初余额是从不同的表中获取的。
我怎样才能完成这个?
最佳答案
您可以将初始本地@Total 变量设置为您的初始余额。来自您的 SQLFiddle:
set @depos=0;
set @total=5000;
select
entry_date,
entry_item,
entry_amount,
if( entry_amount>0, @depos:=entry_amount, @depos:=@depos+entry_amount ) as depos_bal,
@total:=@total+entry_amount as net_bal from chequebook
order by entry_date;
如果它来自不同的查询,则以这种方式设置变量。
关于mysql - 将期初余额添加到 MySQL 中的第一个期末余额行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30492387/