tsql - SQL Server 2008 Column to Row Data -
i have budget table in sql server database looks following:
create table #cols ( acctid int, yr int, pd01 numeric(15,2), pd02 numeric(15,2), pd03 numeric(15,2), . . . pd13 numeric(15,2), primary key(acctid, yr));
i need take data in various columns , switch row based format table following:
create table #rows ( acctid int, yr int, pd int, amt numeric(15,2), primary key(acctid, yr, pd));
now run 13 sql statements this:
insert #rows select acctid, yr, 1, pd01 #cols; . . . insert #rows select acctid, yr, 13, pd13 #cols;
but wondering if there more efficient/elegant way this?
another option unpivot
select acctid,yr,cast(right(pd,2) int) pd, amt #cols unpivot (amt pd in ([pd01],[pd02],[pd03],..., [pd13])) unp