27,579
社区成员
发帖
与我相关
我的任务
分享
select *,(select sum(收入-支出) from 表 where 你的表的主键<=tem.你的表的主键) 本次余额 from 表 tem
create table table1(id int, DDATE varchar(10), IQTYIN int,IQTYOUT int ,IQTYBALANCE int)
go
insert into table1
select 1 ,'1-1', 200,null,null union all
select 2 ,'1-2', 300,null,null union all
select 3 ,'1-3', null,100,null union all
select 4 ,'1-4', 150,null,null union all
select 5 ,'1-5', null,200,null
go
select id,ddate,
IQTYIN,IQTYOUT,
(select sum(isnull(IQTYIN,0))-sum(isnull(IQTYOUT,0)) from table1 t2 where t1.id>=t2.id) as IQTYBALANCE
from table1 t1
/*
id ddate IQTYIN IQTYOUT IQTYBALANCE
1 1-1 200 NULL 200
2 1-2 300 NULL 500
3 1-3 NULL 100 400
4 1-4 150 NULL 550
5 1-5 NULL 200 350
*/
create table table1(id int, DDATE varchar(10), IQTYIN int,IQTYOUT int ,IQTYBALANCE int)
go
insert into table1
select 1 ,'1-1', 200,null,null union all
select 2 ,'1-2', 300,null,null union all
select 3 ,'1-3', null,100,null union all
select 4 ,'1-4', 150,null,null union all
select 5 ,'1-5', null,200,null
go
select id,ddate,
IQTYIN,IQTYOUT,
(select sum(isnull(IQTYIN,0))-sum(isnull(IQTYOUT,0)) from table1 t2 where t1.id>=t2.id) as IQTYBALANCE
from table1 t1
/*
id ddate IQTYIN IQTYOUT IQTYBALANCE
1 1-1 200 NULL 200
2 1-2 300 NULL 500
3 1-3 NULL 100 400
4 1-4 150 NULL 550
5 1-5 NULL 200 350
*/
[/quote]
我测试了一下,居然可以,sql语句可以这样写也是,也真是高手