当前位置: 代码迷 >> Sql Server >> 求一SQL语句 疑难解决方案
  详细解决方案

求一SQL语句 疑难解决方案

热度:69   发布时间:2016-04-27 15:46:54.0
求一SQL语句 疑难
如下结构:
s       r  
1       1
1       2
1       3
1       4
1       5
1       6
s,r主键
删除1,2   和   1,4行数据,并且保持r连续
结果应为:
s       r     t
1       1     a  
1       2     c  
1       3     e
1       4     f
最好批处理


------解决方案--------------------
create table a
(
s int,
r int
)
insert into a
select 1,1 union
select 1,2 union
select 1,3 union
select 1,4 union
select 1,5 union
select 1,6

delete from a where (s=1 and r=2) or (s=1 and r=4)

update a
set a.r= c.cnt
from a inner join
(
select b.s,b.r,cnt=(select count(1) from a where a.s=b.s and a.r <=b.r)
from a b
) c on a.s=c.s and a.r=c.r

select * from a
--结果
s r
----------- -----------
1 1
1 2
1 3
1 4

(4 行受影响)
  相关解决方案