A_first B_first C_first A_second B_second C_second A_third B_third C_third
638 450 188 638 439 187 546 256 789
I have a table like that with only one row. How can I pivot this row so I get A B C as columns and a row for each _first, _second, _third?
I’m trying to wrap my head around the pivot/unpivot command in sql
A B C
638 450 188
638 439 187
546 256 789
Using SQL Server 2008 so I have the pivot/unpivot command. More specifically SSMS tells me the database I’m connected to is 9.0 SP3
You did not specify what RDBMS you are using so here are two solutions. If you have an
UNPIVOTfunction and then aPIVOT:See SQL Fiddle with Demo
If you do not have an
UNPIVOTandPIVOTfunction, then you can useUNION ALL:See SQL Fiddle with Demo
Both will produce the same result:
Note, in order to perform this task the data types must be the same on each column. If they are not then you will need to
convertthe data first prior to theUNPIVOT.This answer makes a few assumptions:
A,BorC, etc)before the row number.