Reputation: 259
Basically what I am trying to do is transpose every other column to a row with the following columns data beside it.
The source can have only two columns up to one-thousand and millions of rows. I am only doing this on a per-row basis. I have tried doing a "UNION ALL" however this is incredibly slow when dealing with hundreds of columns in a large table.
Possible solutions are using UNPIVOT although every example I can find is doing something different from what I want.
Example: Before Query
Columns...
Apple | Apple Data | Banana | Banana Data | Cranberry | Cranberry Data | ....
Data Returned...
IOWA_PL_RLA | 1 | IOWA_PL_MATH | 1 | IOWA_SS_RLA 684 .....
Example: After Query
MeasureID Score
CRCT_PL_RLA | 1
CRCT_PL_MATH | 1
CRCT_SS_RLA |684
.....
Hopefully I have explained myself enough that someone can help as I am only moderately experienced in T-SQL. If more information is needed please let me know.
Upvotes: 3
Views: 1038
Reputation: 89671
If you are using SQL Server 2008, I think you should look into using the CROSS APPLY (VALUES) technique:
http://www.sqlservercentral.com/articles/CROSS+APPLY+VALUES+UNPIVOT/91234/
Basically, it goes like this:
SELECT
x.NewColumn1,
x.NewColumn2
FROM YourTable t
CROSS APPLY (
VALUES
(t.OldColumn1, t.OldColumn2),
(t.OldColumn3, t.OldColumn4),
...
) x (NewColumn1, NewColumn2);
Here's a runnable example: http://sqlfiddle.com/#!3/9a9d2/5/0
Upvotes: 13