sql逐行计算的问题

来源:百度知道 编辑:UC知道 时间:2024/07/02 10:37:45
假设有一个表table1
内有
id t1 t2
1 100
2 40
3 30
4 50
5 60

想生成一个表table2
id t1 t2 value
1 100 100
2 40 60
3 30 90
4 50 40
5 60 -20
就是每一列计算t1-t2的值得最终剩余数
第二个表我是查询得到的结果 我用的Accsee

mr_shj的算法简洁有效,但没有排除null值和保留字value,这里再完善一下。
--如果仅仅是查出来,那么用以下语句
select id,T1,T2,(select sum(iif(isnull(t1),0,t1))-sum(iif(isnull(t2),0,t2)) from table1 where table1.id<=table0.id) as [value] from table1 as table0

--如果要将查出的结果保存到table2中,则:
select id,T1,T2,(select sum(iif(isnull(t1),0,t1))-sum(iif(isnull(t2),0,t2)) from table1 where table1.id<=table0.id) as [value] into table2 from table1 as table0

以上在ACCESS2003中测试通过。

select T1,T2,(select sum(t1)-sum(t2) from table1 where table1.id<=table0.id) as value from table1 as table0

insert into table2
select t1,t2,isnull(t1,0)-isnull(t2,0) as value from table1