select a,b=(select sum(a) from tb where a<=t.a) from tb as t
create table TT ( a int, b int ) insert into TT select 1,1 insert into TT select 3,4 insert into TT select 5,9 insert into TT select 6,15create proc Get_B ( @a int ) as select identity(int,1,1) ID,* into #1 from TT select sum(a) from #1 where ID<=(select ID from #1 where a=@a)--当a等于5 exec Get_B 5----------- 9
--> 生成测试数据表:tbIF NOT OBJECT_ID('[tb]') IS NULL DROP TABLE [tb] GO CREATE TABLE [tb]([a] INT,[b] INT) INSERT [tb] SELECT 1,1 UNION ALL SELECT 3,4 UNION ALL SELECT 5,9 UNION ALL SELECT 6,15 GO --SELECT * FROM [tb]-->SQL查询如下:select a.a,SUM(b.b) b from tb a left join tb b on a.a>=b.a group by a.a /* a b 1 1 3 5 5 14 6 29 */
高手速度就是快,可能我没有表达清楚。我的意思是数据表中只有a列,b列是我想要根据a列查询出来的数据。 例如 b 列的第2行=a的第1行+a的第2行=1+3=4 b 列的第3行=a的第1行+a的第2行+a的第2行=1+3+5=9 。 b想要查询的累加列
from tb as t
(
a int,
b int
)
insert into TT select 1,1
insert into TT select 3,4
insert into TT select 5,9
insert into TT select 6,15create proc Get_B
(
@a int
)
as
select identity(int,1,1) ID,* into #1 from TT
select sum(a) from #1 where ID<=(select ID from #1 where a=@a)--当a等于5
exec Get_B 5-----------
9
DROP TABLE [tb]
GO
CREATE TABLE [tb]([a] INT,[b] INT)
INSERT [tb]
SELECT 1,1 UNION ALL
SELECT 3,4 UNION ALL
SELECT 5,9 UNION ALL
SELECT 6,15
GO
--SELECT * FROM [tb]-->SQL查询如下:select a.a,SUM(b.b) b
from tb a
left join tb b
on a.a>=b.a
group by a.a
/*
a b
1 1
3 5
5 14
6 29
*/
例如 b 列的第2行=a的第1行+a的第2行=1+3=4
b 列的第3行=a的第1行+a的第2行+a的第2行=1+3+5=9
。
b想要查询的累加列
1 1 1 1
3 4 10 11
5 9 20 31
6 15 3 34
10 25 5 39
20 45 6 45a的顺序变了 程序中a列要严格按顺序排列
order by right('0000' & a.a,4)
结贴