2011-01-13 73 views
1

我有一個帶有exp和imp列的ms-access 2003表。在這些exp和imp列中,我有75個國家。我想在同一個表中創建虛擬變量exp1-exp75,imp1-imp75,顯示哪個國家是exp以及哪個國家是imp。例如,如果exp是澳大利亞(澳大利亞是第一個國家),那麼exp1必須是1,所有其他exp2-exp75應該是0.如果imp是英國(UK是第五國),imp5應該是1,其他所有其他小鬼的應該是0,所以這個表應該是這樣的(如果美國是第三和意大利是17國)用0和1填充幾列(創建虛擬變量)

exp   imp exp1 exp2 ...exp17 ... exp75 imp1 imp2 imp3 ... imp5 ... imp75 


Australia  UK  1 0  0   0  0 0 0  1  0 


Italy   USA  0 0  1   0  0 0 1  0  0 

感謝。

+2

對於這樣一個可怕的桌子設計,你有什麼屬世理性嗎?我假設你必須有一個.... – RolandTumble 2011-01-13 19:01:29

回答

0

我在Access 2007編輯器中寫了這個,但是VBA應該是一樣的。我不認爲你可以用查詢做到這一點。

Private Sub FillTable() 

Const firstCountry As Integer = 1 
Const lastCountry As Integer = 75 
Const maxRows  As Integer = 234 'or whatever you need... 


Dim impCountry As Integer 
Dim expCountry As Integer 

Dim db As DAO.Database 
Dim rs As DAO.Recordset 
Dim i As Integer 

Dim j As Integer 

    'function Random1to75 is left as an exercise for the reader 
    impCountry = Random1to75 
    expCountry = Random1to75 

    Do Until expCountry <> impCountry 
     expCountry = Random1to75 
    Loop 

    Set db = CurrentDb() 
    Set rs = db.OpenRecordset("select * from YourTable", dbOpenDynaset) 

    For j = 1 To maxRows 
     rs.AddNew 
      For i = firstCountry To lastCountry 
       If i <> impCountry Then 
        rs("imp" & i) = 0 
       Else 
        rs("imp" & i) = 1 
       End If 

       If i <> expCountry Then 
        rs("exp" & i) = 0 
       Else 
        rs("exp" & i) = 1 
       End If 
      Next 
     rs.Update 
    Next 

    rs.Close 
    Set rs = Nothing 
    Set db = Nothing 

End Sub