已知表结构 C(C1, C2, C3), 其中 C1 为自增列,数据如下:
现想根据已知数据生成 C4 字段:
当 C1 = 1 时 C4 = 10 - 2 = 8
当 C1 = 2 时 C4 = (20 + 10) - (10 + 2) = 18
当 C1 = 3 时 C4 = (30 + 20 + 10) - (10 + 10 + 2) = 38
当 C1 = 4 时 C4 = (30 + 30 + 20 + 10) - (10 + 10 + 10 + 2) = 58
也就是说 C4 的值是 SUM(C2-C3), 但不包括当前值以后的值,对应的 SQL 语句如下:
select c1,c2,c3,(
select sum(c2-c3)
from c cb
where cb.c1<=ca.c1) c4
from c ca
最终结果:
对于 C1 没有索引的情况下,比如数据为:
这种情况可以采用临时表或表变量的方法,把数据先导入到临时表或表变量,并增加一自增列,临时表语句如下:
create table #tmp
(
ta int identity(1,1),
c1 int,
c2 int,
c3 int
)
insert into #tmp (c1,c2,c3) select c1,c2,c3 from c
select c1, c2, c3,(
select sum(c2-c3)
from #tmp cb
where cb.ta<=ca.ta) c4
from #tmp ca
drop table #tmp
表变量语句如下:
declare @tmp table
(
ta int identity(1,1),
c1 int,
c2 int,
c3 int
)
insert into @tmp (c1,c2,c3) select c1,c2,c3 from c
select c1, c2, c3,(
select sum(c2-c3)
from @tmp cb
where cb.ta<=ca.ta) c4
from @tmp ca
最终结果:
C1 | C2 | C3 |
1 | 10 | 2 |
2 | 20 | 10 |
3 | 30 | 10 |
4 | 30 | 10 |
现想根据已知数据生成 C4 字段:
当 C1 = 1 时 C4 = 10 - 2 = 8
当 C1 = 2 时 C4 = (20 + 10) - (10 + 2) = 18
当 C1 = 3 时 C4 = (30 + 20 + 10) - (10 + 10 + 2) = 38
当 C1 = 4 时 C4 = (30 + 30 + 20 + 10) - (10 + 10 + 10 + 2) = 58
也就是说 C4 的值是 SUM(C2-C3), 但不包括当前值以后的值,对应的 SQL 语句如下:
select c1,c2,c3,(
select sum(c2-c3)
from c cb
where cb.c1<=ca.c1) c4
from c ca
最终结果:
C1 | C2 | C3 | C4 |
1 | 10 | 2 | 8 |
2 | 20 | 10 | 18 |
3 | 30 | 10 | 38 |
4 | 30 | 10 | 58 |
对于 C1 没有索引的情况下,比如数据为:
C1 | C2 | C3 |
1 | 10 | 2 |
4 | 20 | 10 |
3 | 30 | 10 |
2 | 30 | 10 |
这种情况可以采用临时表或表变量的方法,把数据先导入到临时表或表变量,并增加一自增列,临时表语句如下:
create table #tmp
(
ta int identity(1,1),
c1 int,
c2 int,
c3 int
)
insert into #tmp (c1,c2,c3) select c1,c2,c3 from c
select c1, c2, c3,(
select sum(c2-c3)
from #tmp cb
where cb.ta<=ca.ta) c4
from #tmp ca
drop table #tmp
表变量语句如下:
declare @tmp table
(
ta int identity(1,1),
c1 int,
c2 int,
c3 int
)
insert into @tmp (c1,c2,c3) select c1,c2,c3 from c
select c1, c2, c3,(
select sum(c2-c3)
from @tmp cb
where cb.ta<=ca.ta) c4
from @tmp ca
最终结果:
C1 | C2 | C3 | C4 |
1 | 10 | 2 | 8 |
4 | 20 | 10 | 18 |
3 | 30 | 10 | 38 |
2 | 30 | 10 | 58 |