SELECT *,(SELECT SUM(A) FROM B WHERE ID<T.ID)AS 和 FROM B T?
---------------------------------------------------------------- -- Author :fredrickhu(我是小F,向高手学习) -- Date :2010-01-14 13:47:17 -- Version: -- Microsoft SQL Server 2005 - 9.00.4035.00 (Intel X86) -- Nov 24 2008 13:01:59 -- Copyright (c) 1988-2005 Microsoft Corporation -- Developer Edition on Windows NT 5.2 (Build 3790: Service Pack 1) -- ---------------------------------------------------------------- --> 测试数据:[tb] if object_id('[tb]') is not null drop table [tb] go create table [tb]([id] int,[a] int) insert [tb] select 1,10 union all select 2,20 union all select 3,30 union all select 4,40 union all select 5,50 --------------开始查询-------------------------- select sum(a) from [tb] where id<3 ----------------结果---------------------------- /* ----------- 30(1 行受影响) */
if object_id('[B]') is not null drop table [B] go create table [B]([id] int,[a] int) insert [B] select 1,10 union all select 2,20 union all select 3,30 union all select 4,40 union all select 5,50select * from bselect t1.id,t1.a,(select sum(a) from B t2 where t2.id<t1.id) from b t11 10 NULL 2 20 10 3 30 30 4 40 60 5 50 100
-- Author :fredrickhu(我是小F,向高手学习)
-- Date :2010-01-14 13:47:17
-- Version:
-- Microsoft SQL Server 2005 - 9.00.4035.00 (Intel X86)
-- Nov 24 2008 13:01:59
-- Copyright (c) 1988-2005 Microsoft Corporation
-- Developer Edition on Windows NT 5.2 (Build 3790: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([id] int,[a] int)
insert [tb]
select 1,10 union all
select 2,20 union all
select 3,30 union all
select 4,40 union all
select 5,50
--------------开始查询--------------------------
select sum(a) from [tb] where id<3
----------------结果----------------------------
/* -----------
30(1 行受影响)
*/
if object_id('[B]') is not null
drop table [B]
go
create table [B]([id] int,[a] int)
insert [B]
select 1,10 union all
select 2,20 union all
select 3,30 union all
select 4,40 union all
select 5,50select * from bselect t1.id,t1.a,(select sum(a) from B t2 where t2.id<t1.id) from b t11 10 NULL
2 20 10
3 30 30
4 40 60
5 50 100