日期:2014-05-17  浏览次数:20478 次

这条语句,请教高手!
要实现这样的功能
字段
NAME B C D
a 20 23 43
a 28 43 71
b 36 20 56
b 13 56 69
……
B+C=D,然后D值赋给下一行C怎么写?
急!


------解决方案--------------------
SQL code

--> 测试数据:[test]
if object_id('[test]') is not null drop table [test]
go 
create table [test]([NAME] varchar(1),[B] int,[C] int)
insert [test]
select 'a',20,23 union all
select 'a',28,43 union all
select 'b',36,20 union all
select 'b',13,56
go

;with t
as(
select px=row_number()over(partition by [NAME] order by getdate()),
* from test
)
select [NAME],[B],
isnull((select [B]+[C] from t a where a.px=b.px-1 and a.[NAME]=b.[NAME]),[C]) as [C],
[B]+[C] as [D]
from t b
/*
[NAME] [B] [C] [D]
-----------------------------------
a    20    23    43
a    28    43    71
b    36    20    56
b    13    56    69
*/

------解决方案--------------------
SQL code

-->try
declare @test table(name varchar(1),B int,C int,D int)
insert into @test
select 'a', 20, 23, 43 union all
select 'a', 28, null, 71 union all
select 'b', 36, 20, 56 union all
select 'b', 13, null, 69
;with cte as
(
    select row_number() over(partition by name order by name) rn,* from @test
)
select name,B,C=isnull((select D from cte where t.rn>rn and t.name=name),C),D from cte t
/*
name B           C           D
---- ----------- ----------- -----------
a    20          23          43
a    28          43          71
b    36          20          56
b    13          56          69
*/