I have a table with 52 columns now I need to transpose columns which contain Date
Input:
2009 2010 2011 2012
30 50 60 80
Output:
Year Values
2009 30
2010 50
2011 60
2012 80
I have a table with 52 columns now I need to transpose columns which contain Date
Input:
2009 2010 2011 2012
30 50 60 80
Output:
Year Values
2009 30
2010 50
2011 60
2012 80
Suggestion 1: Copy the data out, stick it in excel, then copy and Paste-Special>>Transpose. Then copy it back into a new table in Access
Suggestion 2: VBA. Assuming your table has a single record with many many many fields something like the following would work:
Sub transpose()
Dim rs As Recordset
Dim rsField As Field
Dim db As Database
Dim StrSQL As String
Set db = CurrentDb
Set rs = db.OpenRecordset("SELECT * FROM Table1", dbOpenTable)
'Assuming that there is only 1 record
For Each rsField In rs.Fields
StrSQL = "INSERT INTO Table2 VALUES ('" & rsField.Name & "'," & rsField.Value & ");"
Next rsField
End Sub
Table1
has the single record with many many fields. Table2
has two fields (YEAR
and VALUE
)
Suggestion 3: 1 Really really horrible UNION query:
SELECT "2009" as year, [2009] as value FROM Table1
UNION ALL
SELECT "2010" as year, [2010] as value FROM Table1
UNION ALL
SELECT "2011" as year, [2011] as value FROM Table1
UNION ALL
SELECT "2012" as year, [2012] as value FROM Table1
Conclusion: All of these are terrible, but so is your data. The excel solution is very manual and excel might destroy your data (removing leading 0's, converting date formats, other awful things). Solution 2 means you have to write and maintain VBA... and Solution 3 is just a pain to write and isn't easily repeatable if you have other similar tables, but with different data that you need to unpivot.