当前位置: 代码迷 >> Sql Server >> 求一交叉减数SQL解决方法
  详细解决方案

求一交叉减数SQL解决方法

热度:41   发布时间:2016-04-27 14:22:00.0
求一交叉减数SQL
表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。。。

------解决方案--------------------
SQL code
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)
------解决方案--------------------
SQL code
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*/
  相关解决方案