表1,
C A b
扶手 12 10
扶手 9 9
扶手 9 9
扶手 8 8
扶手 8 7
扶手 6 6
要的输入结果:
C A B
扶手 12 10 1
扶手 9 9 0
扶手 9 9 0
扶手 8 8 0
扶手 8 7 1
扶手 6 6第一条B,第去第二条A
C A b
扶手 12 10
扶手 9 9
扶手 9 9
扶手 8 8
扶手 8 7
扶手 6 6
要的输入结果:
C A B
扶手 12 10 1
扶手 9 9 0
扶手 9 9 0
扶手 8 8 0
扶手 8 7 1
扶手 6 6第一条B,第去第二条A
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-1C 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
*/