读书人

这条语句

发布时间: 2012-09-10 11:02:33 作者: rapoo

这条语句,请教高手!
要实现这样的功能
字段
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 allselect 'a',28,43 union allselect 'b',36,20 union allselect 'b',13,56go;with tas(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    43a    28    43    71b    36    20    56b    13    56    69*/
[解决办法]
SQL code
-->trydeclare @test table(name varchar(1),B int,C int,D int)insert into @testselect 'a', 20, 23, 43 union allselect 'a', 28, null, 71 union allselect 'b', 36, 20, 56 union allselect '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          43a    28          43          71b    36          20          56b    13          56          69*/ 

读书人网 >SQL Server

热点推荐