2016-06-30 89 views
0
許多關係

我的問題是給定一個一對多的關係船,那裏的小朋友都存儲在1 ChildTable,訪問SQL的1:更新兒童以標準爲基礎

ChildID | ParentID | Data2 | InputDate 
------------------------------------ 
    1  | 345  | 100 | 3-5-2016 
    2  | 345  | 0 | 3-12-2016 
    3  | 345  | 150 | 3-19-2016 
    4  | 345  | 0 | 4-20-2016 
... more children with different parent IDs 

,並考慮到父母存儲在他們自己的ParentTable與ParentID ...數據等

我的問題是如何分區或更新查詢類似的數據庫,以便如果數據列的值爲0,然後它更新與最後輸入的數據。 (比如網絡抓取工具無法提取數據,我想近似分析)。原始數據不必在基表上更新,但也可以在查詢中更新。我相信有一種使用SQL來實現這一點的方法。我的嘗試速度非常慢,並且因爲未知原因而無法工作。

我試過編寫一些VBA訪問代碼來循環瀏覽平面文件ChildTable + ParentTable並更新列中的每個0值單元格數據使用一個SQL查找。如果單元格= 0,則轉到最後一個非零的可用數據。 這需要幾年才能運行的問題。

Option Compare Database 

Sub SoldOut() 
On Error GoTo ProcError 
Dim rs As DAO.Recordset 
Set rs = CurrentDb.OpenRecordset("MainDataTable") 'This is the flat file version of the data above 

'Check to see if the recordset actually contains rows 
If Not (rs.EOF And rs.BOF) Then 
    rs.MoveLast 
    rs.MoveFirst 'Unnecessary in this case, but still a good habit 
    Do Until rs.EOF = True 
    GetLastWeek = 0 
     If Not rs("Data") > 0 Then 
      rs.Edit 
      rs("Data") = GetLastWeek(rs('ChildID'), rs('ParentID'), rs('Data'), rs('InputDate')) 
      rs.Update 
     End If 

     'Move to the next record. Don't ever forget to do this. 
     rs.MoveNext 
    Loop 
Else 
    MsgBox "There are no records in the recordset." 
End If 

ProcExit: 
On Error Resume Next 
rs.Close 'Close the recordset 
Set rs = Nothing 'Clean up 
Exit Sub 

ProcError: 
    MsgBox Err.Description 
    Resume ProcExit 

End Sub 

Private Function GetLastWeek(ChildID, ParentID As Long, InputDate As Date) As Integer 
    'given a record it looks up the weeks before and returns it if it exists 
    Dim rst As DAO.Recordset, strSQL As String, rc As Integer ' SQL Code for seeing if last week's data exists. 

    strSQL = "SELECT * " & _ 
    "FROM MainDataTable " & _ 
    "WHERE MainDataTable.[ParentId] = " & ParentID & "AND MainDataTable.[InputDate] <# " & InputDate & "AND NOT MainDataTable.[Data] = 0 
    ORDER BY MainDataTable.[InputDate] DESC;" 

    Set rst = CurrentDb.OpenRecordset(strSQL): rst.MoveLast: rst.MoveFirst 
    rc = rst.RecordCount 
    If rc = 0 Then GoTo Cleanup 'if no record, then we are out of luck 
    If rc > 0 Then 'If there's some Record 
     Do Until rs.EOF = True Or GetLastWeek > 0 
      Dim price As Integer: price = rst("Data") 
      If price > 0 Then: GetLastWeek = price 
      rs.MoveNext 
     Loop 
    End If 

Cleanup: 
    rst.Close 
    Set rst = Nothing 
    If GetLastWeek = 0 Then GetLastWeek = 1 '1 means no data was found 
    'Set so the output if nothing is found to 1 so that the code doesn't have to run on the same rows every single week 
End Function 

回答

0

我不知道如何你有什麼可以工作,但你應該做的是通過parentid, date asc訂購了主表迭代,然後保存的parentID和數據值以用於下一次迭代( Dim lDataValPrev as long),只要它不是零。如果當前數據值爲零且parentID未更改,請將其替換爲您存儲的先前值。你只需要一次查看你的數據,不需要額外的電話。

+0

同意。我的想法是按照每個parentID的降序製作一個迷你數據庫。這跑了太久,所以我希望有其他的邏輯。謝謝你! – user3750428