日期:2014-05-17 浏览次数:20486 次
--> 测试数据:[tb] IF OBJECT_ID('[tb]') IS NOT NULL DROP TABLE [tb] GO CREATE TABLE [tb]([a] INT,[b] INT,[c] INT) INSERT [tb] SELECT 1,10,NULL UNION ALL SELECT 2,1,NULL UNION ALL SELECT 3,2,NULL UNION ALL SELECT 4,1,100 --------------开始查询-------------------------- --1 SELECT [a],[b],[c]=100+ISNULL((SELECT SUM([b]) FROM [tb] WHERE [a]>t.[a]),0) FROM [tb] AS t --2 SELECT [a],[b],[c]=app.[c]+ISNULL((SELECT SUM([b]) FROM [tb] WHERE [a]>t.[a]),0) FROM [tb] AS t CROSS APPLY(SELECT TOP 1 ISNULL([c],0) AS [c] FROM [tb] ORDER BY [a] DESC ) app ----------------结果---------------------------- /* a b c 1 10 104 2 1 103 3 2 101 4 1 100 */
------解决方案--------------------
create table hb (a int,b int,c int) insert into hb select 1, 10, null union all select 2, 1, null union all select 3, 2, null union all select 4, 1, 100 declare @sql varchar(6000) select @sql=' update t1 set t1.c= (select t2.c+t2.b from hb t2 where t2.a=t1.a+1) from hb t1 where t1.c is null' exec(@sql) while @@rowcount>0 exec(@sql) -- 结果 select * from hb /* a b c ----------- ----------- ----------- 1 10 104 2 1 103 3 2 101 4 1 100 (4 row(s) affected) */