Monday, 7 April 2014

SQL Result as vertical

create table test (CustomerID int,CustomerName varchar(50),Location varchar(50))
Insert into test values (101,'IBM','NY'),(102,'MSFT','WA')
select * from test
--Method-1
Select Col,Val from test
cross apply (values('customerID',Cast(customerID as varchar(50))),('CustomerName',CustomerName),('Location',Location) ) d(Col,Val)


--Method-2
Select Col,Val from (select Cast(customerID as varchar(50)) as customerID,CustomerName,Location from test) src
unpivot (val For col in ([customerID],[CustomerName],[Location])) unpvt

drop table test

No comments:

Post a Comment