Combining rows and columns in SQL

Viewed 45

I am trying to convert my rows into columns, or my columns into rows... I am a little confused with which it is exactly but here's what I would want it to look like

Original table:

Month | Price
1       500  
2       600
3       700

what it needs to look like:

 1     2     3
500   600   700

Could anyone tell me how his could be done?

EDIT:

CREATE table #yourtable     (
   [Id] int, 
   [Value] varchar(6), 
   [ColumnName] varchar(13)) ;      
INSERT INTO #yourtable     (
   [Id], 
   [Value], 
   [ColumnName]) 
VALUES     
   (1, '1', 'Month'),     
   (2, '500', 'Price') ;   

select 
   Month, 
   Price 
from (   
   select 
      value, 
      columnname   
   from #yourtable ) d 
pivot 
  (max(value)   for columnname in (Month, Price) ) piv;
1 Answers

You wrote an almost correct query.

select 
    Month, 
   Price 
from (   
   select 
      value, 
      columnname   
   from #yourtable) d 
pivot 
  (max(value)   for columnname in ('Month' AS Month, 'Price' AS Price) ) piv;
Related