我有下表:
VehicleID Reg_ID Next_RegID EntryDate
330034 9111 NULL 2010-12-06 00:00:00
330034 9113 NULL 2010-12-09 00:00:00
在第一行,我需要使用第二行的Reg_ID更新Next_RegId列,其中VehicleId或(VIN / ChassisNumber)相同。最后一个条目的Next_RegID列应保持为空。
我已经创建了一个完美的while循环程序,但是表中有数百万条记录需要很长时间才能完成。因此,我想知道你们中是否有人处理过这类问题而且有解决方案。
这是我写的程序,并提前感谢您的所有帮助:
Declare @i as integer;
Declare @x as integer;
Declare @y as integer
Set @i= (Select Max(RID) from TempRegistration)
Set @x= 0
Set @y= 1
Declare @curChassis as nvarchar(100)
Declare @nextChassis as nvarchar(100)
While (@x <= @i)
Begin
set @curChassis = (Select ChassisNumber from TempRegistration where RID = @x)
set @nextChassis = (Select ChassisNumber from TempRegistration where RID = @y)
If (@curChassis = @nextChassis)
Begin
Update Registration set NextRegistrationId = (Select RegistrationId from TempRegistration where RID = @y)
Where RegistrationId = (Select RegistrationId from TempRegistration where RID = @x)
End
Set @x = @x + 1
Set @y = @y + 1
Print(@x)
End
TempRegistration是我创建的一个临时表,用于分配一个row_id,引导while循环将Reg_ID分配给前一行的Next_RegId。
答案 0 :(得分:0)
这可以通过一个UPDATE查询来完成。你没有提到你的RDBMS ......
对于MSSQL:
Update Registration as t1
set NextRegistrationId = (Select TOP 1 RegistrationId
from Registration
where RID = t1.RID
and EntryDate>t1.EntryDate
order by EntryDate DESC)
对于MySQL
Update Registration as t1
set NextRegistrationId = (Select RegistrationId
from Registration
where RID = t1.RID
and EntryDate>t1.EntryDate
order by EntryDate DESC
LIMIT 1)
如果RID随着EntryDate的增加而增加
Update Registration as t1
set NextRegistrationId = (Select MIN(RegistrationId)
from Registration
where RID = t1.RID
and EntryDate>t1.EntryDate
)
答案 1 :(得分:0)
经过测试,它似乎正在运行,但此版本使用CTE
(SQL Server)
with RegDetails as
(
select VehicleID, Reg_ID, ROW_NUMBER() OVER(PARTITION BY VehicleID ORDER BY EntryDate) AS ROWNUMBER
FROM dbo.Vehicle)
UPDATE a SET a.Next_RegID = b.Reg_ID
FROM RegDetails b
INNER JOIN dbo.Vehicle a ON (a.VehicleID = b.VehicleID)
WHERE b.ROWNUMBER = 2 and a.Next_RegID IS NULL and a.Reg_ID != b.Reg_ID