日期:2014-05-18 浏览次数:20561 次
create table xav (C varchar(6), A int, B int) insert into xav select '扶手', 12, 10 union all select '扶手', 9, 9 union all select '扶手', 9, 9 union all select '扶手', 8, 8 union all select '扶手', 8, 7 union all select '扶手', 6, 6 with t as (select row_number() over(order by (select 0)) rn,C,A,B from xav ) select t1.C,t1.A,t1.B,isnull(cast(t1.B-t2.A as varchar),'') 'BA' from t t1 left join t t2 on t1.rn=t2.rn-1 C A B BA ------ ----------- ----------- ------------------------------ 扶手 12 10 1 扶手 9 9 0 扶手 9 9 1 扶手 8 8 0 扶手 8 7 1 扶手 6 6 (6 row(s) affected)
------解决方案--------------------
drop table #t create table #t(C nvarchar(4), A int, B int) insert into #t select N'扶手', 12, 10 union all select N'扶手', 9, 9 union all select N'扶手', 9, 9 union all select N'扶手', 8, 8 union all select N'扶手', 8, 7 union all select N'扶手', 6, 6 with ct as (select *,ROW_NUMBER() Over ( order by A desc) rw from #t) select t1.C,t1.A,t1.B, t1.B - t2.A as cal from ct t1 left join ct t2 on t1.rw = t2.rw -1 /* C A B cal 扶手 12 10 1 扶手 9 9 0 扶手 9 9 1 扶手 8 8 0 扶手 8 7 1 扶手 6 6 NULL */