I want to transpose rows into columns in ms-access

前端 未结 3 458
太阳男子
太阳男子 2021-01-26 00:57

I need to transpose rows into columns in MS Access database, VBA, SQL both the codes are welcome.

Table

    | Name | Ticker | ID | Innovation | Quality |         


        
3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-26 01:48

    This is a vb script that takes the data from TableSource and transposes it into TableTranspose. The 2nd table has to be set up with a column named FName to take the field names, and columns for each year in the source table.

    Function Transpose()
    Set db = CurrentDb()
    db.Execute ("delete * from TableTranspose")
    Set RS = db.OpenRecordset("TableSource")
    Set YrList = db.OpenRecordset("select distinct [Yr] from [TableSource] Group by [Yr]")
    
    For Each F In RS.Fields
        FN = F.Name
        INS = "Insert Into TableTranspose (FName"
        SQL = "Select '" & FN & "'"
        YrList.MoveFirst
        Do While Not YrList.EOF
            YR = YrList.Fields("YR").Value
            INS = INS & ",[" & YR & "]"
            SQL = SQL & ",max(iif(YR=" & YR & ",[" & FN & "])) AS [" & YR & "]"
            YrList.MoveNext
            Loop
        SQL = SQL & " From TableSource"
        db.Execute (INS & ") " & SQL)
    
    Next F
    MsgBox ("Done")
    End Function
    

    This works by processing one field at a time to match the layout of the desired output, and looping through each year of TableSource to find the data to make up the row in TableTranspose. It shouldn't matter how many fields there are or what they are named.

    It will create a row in the output for the Year, which will be redundant - you can delete it, or add logic to skip that field if necessary.

    This seems to work fine with the 4 years of data in your sample, and should extend OK to more years. It's possible that you will hit a limit on SQL command length if there are too many years in the data, but I think not.

    If you are filtering the records from TableSource, you can add the WHERE clause on the line just from the db.execute near the bottom.

提交回复
热议问题