首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

sql语句实现上面效果

2012-12-15 
求一个sql语句实现下面效果idnum1num210.150.1520.250.4030.350.7540.100.85上面逻辑为 num2为他id以上列n

求一个sql语句实现下面效果
id  num1   num2
1   0.15   0.15
2   0.25   0.40
3   0.35   0.75
4   0.10   0.85


上面逻辑为 num2为他id以上列num1的和

如上,是查询出来的结果,现在数据源只有id和num1列,如果计算出num2列

求一个sql语句查询出如上结果

多谢!!!  感激不尽
[最优解释]

create table #TB(id int,num1 float)
insert into #TB 
select 1,0.15
union all
select 2,0.25
union all
select 3,0.35
union all
select 4,0.10
---测试

select ID,num1,(select SUM(num1) from #TB where id<=a.id) as num2
from #TB as a 

[其他解释]
用CTE也可以
[其他解释]
引用:
SQL code

12345678910111213

create table #TB(id int,num1 float) insert into #TB  select 1,0.15 union allselect 2,0.25 union allselect 3,0.35 union allselect 4,0.10 ---测试   select ID,num1,(sel……


真的不错很好用 是最简单的  也可以用游标
[其他解释]
select id,num1,num2=(select sum(num1) from tb where id<a.id) from tb a
 
[其他解释]
谢谢各位!!!

热点排行