我有一个很大的数据文件,在每个相关子集的第一条记录上具有唯一的11位数字引用,但在属于相同子集的后续记录上没有,具有伪造的1位或2位数字引用。该表的顺序与创建时的顺序相同,因此子集仍正确地分组在一起,并且包含这些引用的字段称为“旧引用”。我刚刚创建了一个名为“ New Ref”的新字段,我想为每个子集填充所有适当的11位数字引用。我可以在PL / pgSQL上运行的脚本中如何最好地实现这一点?
以下是数据的示例(当前),我希望对其进行更新:
Current datafile
__________________________________
ID | Old Ref | New Ref
==================================
1 | 14740807000 |
2 | 1 |
3 | 2 |
4 | 3 |
5 | 58 |
6 | 14735113000 |
7 | 1 |
8 | 2 |
9 | 39 |
10 | 4 |
11 | 5 |
12 | 14915146000 |
13 | 9 |
14 | 27 |
15 | 14915146000 |
16 | 3 |
17 | 4 |
==================================
Sought updated datafile
__________________________________
ID | Old Ref | New Ref
==================================
1 | 14740807000 | 14740807000
2 | 1 | 14740807000
3 | 2 | 14740807000
4 | 3 | 14740807000
5 | 58 | 14740807000
6 | 14735113000 | 14735113000
7 | 1 | 14735113000
8 | 2 | 14735113000
9 | 39 | 14735113000
10 | 4 | 14735113000
11 | 5 | 14735113000
12 | 14915146000 | 14915146000
13 | 9 | 14915146000
14 | 27 | 14915146000
15 | 14915175959 | 14915175959
16 | 3 | 14915175959
17 | 4 | 14915175959
==================================
在MS Access中,我认为这是一种简洁的方法,但是无法处理需要更新的数据文件的大小,这就是我改用PostgreSQL的原因之一。 / p>
这是MS Access脚本:
Sub UpdateRef()
On Error GoTo ErrorHandler
Dim strSQL, Var1 As String
Dim rs As New ADODB.Recordset
rs.Open "SELECT test.* FROM test", CurrentProject.Connection, adOpenDynamic, adLockOptimistic
rs.MoveFirst
Var1 = rs![Old ref]
rs![New Ref] = Var1
rs.Update
Do Until rs.EOF
'SysCmd acSysCmdUpdateMeter, n
If len(rs![Old ref]) > 2 Then
Var1 = rs![field2]
End If
rs![New Ref] = Var1
rs.Update
rs.MoveNext
Loop
rs.Close
ExitSub:
Set rs = Nothing
Exit Sub
ErrorHandler:
Resume ExitSub
End Sub
答案 0 :(得分:0)
您可以使用以下update
语句来做到这一点:
update test t
set newref = (select tt.oldref from test tt where tt.id = (
select max(id) from test where id <= t.id and length(oldref) = 11
));
请参见demo
这个:
select max(id) from test where id <= t.id and length(oldref) = 11
获取包含11位数字id
的行的oldref