求一交叉减数SQL
表1,
C A b
扶手1210
扶手99
扶手99
扶手88
扶手87
扶手66
要的输入结果:
C A B
扶手1210 1
扶手99 0
扶手99 0
扶手88 0
扶手87 1
扶手66
第一条B,第去第二条A。。。
[解决办法]
create table xav(C varchar(6), A int, B int)insert into xavselect '扶手', 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, 6with 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 t1left 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 #tcreate table #t(C nvarchar(4), A int, B int)insert into #tselect N'扶手', 12, 10 union allselect N'扶手', 9, 9 union allselect N'扶手', 9, 9 union allselect N'扶手', 8, 8 union allselect N'扶手', 8, 7 union allselect 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 t2on 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*/