我有一个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 |
从不同的表格中提取期初余额。
我该如何完成?
答案 0 :(得分:1)
您可以将初始本地@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;
如果来自不同的查询,请按此方式设置变量。