日期:2014-05-18  浏览次数:20471 次

条件转换列值难题--急,搞了好久都不会
表A中有shou列(tinyint,其值只可能是0,1,2,3四者之一),现在需要根据shou列的值更新cc列的值,规则如下:
1.当shou列第(N+1)行的数字是1时,cc列第N行的值等于shou列第N行的值。
2.当shou列第N行的数字是3,同时shou列第N+1行的数字是0时,cc列第N行的值等于4。
3.当shou列第N行的数字是3,同时shou列第N+1行的数字是1时,cc列第N行的值等于3。
4.其他情况cc列的值都为0.
------------------
示例如下:
shou列         cc列
1                   1      
1                   0  
2                   2
1                   0
2                   0
3                   3  
1                   0
2                   0  
3                   4
0                   0
1                   0  
2                   2
------------
请教各位大虾!



------解决方案--------------------
create table tb(shou列 int,cc列 int)
insert into tb
select 1,1
union all
select 1,0
union all
select 2,2
union all
select 1,0
union all
select 2,0
union all
select 3,3
union all
select 1,0
union all
select 2,0
union all
select 3,4
union all
select 0,0
union all
select 1,0
union all
select 2,2
select * from tb

create proc dbo.proc_updateDate
as
begin
set nocount on
begin tran
select identity(int,1,1) as ID,* into #tempTb from tb
update #tempTb set cc列=(case when (select shou列 from #tempTb a where a.ID=ID + 1)=1 then shou列
when (shou列=3) and (select shou列 from #tempTb b where b.ID=ID+1)=0 then 4
when (shou列=3) and (select shou列 from #tempTb c where c.ID=ID+1)=1 then 3
else 0 end )
delete tb
insert into tb
select shou列,cc列 from #tempTb
select * from tb
if @@error <> 0
rollback tran
else
commit tran
end

drop table tb
drop proc dbo.proc_updateDate