来自其他行号的T-SQL更新记录

时间:2010-12-13 20:44:47

标签: tsql

在SQL Server 2008中,我有table1,并希望更新表,如第二个表所示。 即从上面的记录更新Rn(2)的更新值1(Rn(1)的值2)。序列由Rn决定。 在这方面的任何帮助将不胜感激。

alt text

非常感谢。

Create table Table1(ID int, value1 int, value2 int, Item varchar(10),Rn int)

insert into Table1(ID,Value2,Item,Rn) values('1','33242','Orange','1')
insert into Table1(ID,Value2,Item,Rn) values('2','67665','Orange','2')
insert into Table1(ID,Value2,Item,Rn) values('3','78765','Orange','3')
insert into Table1(ID,Value2,Item,Rn) values('4','576','Orange','4')
insert into Table1(ID,Value2,Item,Rn) values('5','906658','Orange','5')
insert into Table1(ID,Value2,Item,Rn) values('6','54435','Orange','6')
insert into Table1(ID,Value2,Item,Rn) values('7','7464','Mango','1')
insert into Table1(ID,Value2,Item,Rn) values('8','9876','Mango','2')
insert into Table1(ID,Value2,Item,Rn) values('9','2433','Mango','3')
insert into Table1(ID,Value2,Item,Rn) values('10','5654','Mango','4')
insert into Table1(ID,Value2,Item,Rn) values('11','13213','Mango','5')
insert into Table1(ID,Value2,Item,Rn) values('12','9867867','Mango','6')
insert into Table1(ID,Value2,Item,Rn) values('13','5644355','Mango','7')
insert into Table1(ID,Value2,Item,Rn) values('14','6534','Apple','1')
insert into Table1(ID,Value2,Item,Rn) values('15','343','Apple','2')
insert into Table1(ID,Value2,Item,Rn) values('16','423','Apple','3')
insert into Table1(ID,Value2,Item,Rn) values('17','7666','Apple','4')

4 个答案:

答案 0 :(得分:2)

这将每个“块”的第一行的Value1设置为null。您可以使用ISNULL覆盖它并使其为0,或者任何其他默认值可能是合适的。

;WITH cte (Id, Value1, Value2, Item, Rn, RnPlus1)
 as (select Id, Value1, Value2, Item, Rn, row_number() over (partition by Item order by Rn) + 1 RnPlus1
 from Table1) 
UPDATE Table1
 set Value1 = cte.Value2
 from Table1 t1
  inner join cte
   on cte.Item = t1.Item
    and cte.RnPlus1 = t1.Rn

答案 1 :(得分:0)

由于您尚未定义任何父子关系,因此可能很难。你能在插入时做到这一点(然后可能定义关系......)?

insert into Table1(ID,Value1,Value2,Item,Rn) values('1','','33242','Orange','1')
insert into Table1(ID,Value1,Value2,Item,Rn) values('2','33242','67665','Orange','2')
insert into Table1(ID,Value1,Value2,Item,Rn) values('3','67665','78765','Orange','3')
insert into Table1(ID,Value1,Value2,Item,Rn) values('4','78765','576','Orange','4')

依旧......

答案 2 :(得分:0)

我总是觉得这对屁股来说是一种正确的痛苦。但我会建议一个光标。像这样的东西; (这只是骨架。它不起作用!但你应该能够看到原理)

DECLARE @ field1整数 DECLARE @ fiedl2整数 DECLARE @NewValue整数

SET @NewValue = 0

DECLARE Tab1 CURSOR FOR SELECT * FROM Table1

FETCH NEXT FROM Tab1 INTO @ field1,@ field2

WHILE @@ FETCH_STATUS = 0 BEGIN

IF @NewValue <> 0
    UPDATE Table1 SET field1 = @NewValue

FETCH NEXT FROM Tab1
INTO @field1, @field2

SET @NewValue = @field2

END

关闭Tab1 DEALLOCATE Tab1

答案 3 :(得分:0)

脱离我的头顶,如:

更新table1 t1 set t1.value1 =(从table1 t2中选择t2.value2,其中t2.id = t1.id + 1)其中t1.rn!= 1